简体   繁体   English

试图通过空格传递bash变量

[英]Trying to pass bash variable with spaces

Can anyone help with this query. 任何人都可以帮助这个查询。 Currently attempting to pass a variable into xml using sed. 当前正在尝试使用sed将变量传递到xml中。 This works fine with just the text, however its not picking up the variable within bash such as $1, $2 etc which will need to be inputted by the user. 这仅适用于文本,但是它不会在bash中拾取变量,例如$ 1,$ 2等,这些变量将需要由用户输入。

EG: 例如:

sed 's/<\\/sProblemDesc>/'"anew test"'&/' create.xml

successful output <sProblemDesc>anew test</sProblemDesc> 成功输出<sProblemDesc>anew test</sProblemDesc>

However when inserting a $1 variable between the anew test part, its either bringing back the literal name of the variable and not the data. 但是,在新的测试部分之间插入$ 1变量时,它要么带回变量的字面名称,而不带回数据。

The user will be running the script as such 用户将像这样运行脚本

./script.sh "enter stuff here" "enter more stuff" "21313122131"

So I need to know how to get it to work with the variable but also take into consideration that I am having to use quotes to separate the variables..(if there is another way to do this let me know :D! ) 因此,我需要知道如何使其与变量一起使用,但还要考虑到我必须使用引号将变量分开。(如果还有另一种方法可以让我知道:D!)

Any queries let me know cheers 任何疑问都让我知道欢呼

Update: As requested the variable name is just variablename="$1" 更新:根据要求,变量名称仅为variablename =“ $ 1”

I have tried removing the quotes as well just having =$1 does not seem to work with that either, so I am guessing its because when running the script (./script "stuff here" "etc" "etc" I am using quotes there but not sure how to get round it. 我试图删除引号以及== 1似乎也不能用,所以我猜是因为运行脚本(./script“ stuff here”“ etc”“ etc”时我在这里使用引号但不确定如何解决。

EG 例如

Script 脚本

variablename=$1

sed 's/<\\/sProblemDesc>/'"$variablename"'&/' create.xml

running the script 运行脚本

./script "variablename here" "etc etc" "etc"

XML is blank such as <sProblemDesc></sProblemDesc> XML为空白,例如<sProblemDesc></sProblemDesc>

another example 另一个例子

echo sed 's/<\\/sActionDesc>/'"$variablename"'&/' create.xml

returns the following which is not showing the variable name its just blank 返回以下内容,该内容未显示变量名称,即为空白

sed s/<\\/sActionDesc>/&/ create.xml

Cheers again 再次欢呼

wingZero 翼零

I think there is some other issue, because this simple test works: 我认为还有其他问题,因为此简单测试有效:

$ cat test.sh 
#!/bin/bash
myvar=$1
echo "<sProblemDesc></sProblemDesc>" | sed 's/<\/sProblemDesc>/'"$myvar"'&/'

$ ./test.sh "enter stuff here"
<sProblemDesc>enter stuff here</sProblemDesc>

What does your script do more that this? 您的脚本还可以做什么呢?

This works for me: 这对我有用:

variablename=$1
echo ${variablename}

sed 's/<\/sProblemDesc>/'"${variablename}"'&/' create.xml

eg With the file create.xml as: 例如,文件create.xml为:

hello
<sProblemDesc></sProblemDesc>

this command: 该命令:

./example.sh "here and here" foobar

produces: 产生:

here and here
hello
<sProblemDesc>here and here</sProblemDesc>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM