[英]How can I fix sed invalid command code '?
I have a shell script with below 2 commands: 我有以下2个命令的Shell脚本:
sedcmd1="sed -i '' '/<PromptOnUpdate>true<\/PromptOnUpdate>/G' /Users/abc/data.xml"
$sedcmd1
when I run the script I get below error: 当我运行脚本时,出现以下错误:
sed: 1: "'/<PromptOnUpdate ...": invalid command code '
If I run the command without assigning it to the variable, it runs just fine. 如果我在未将命令分配给变量的情况下运行该命令,则该命令将正常运行。 But I get an error only when I assign it to a variable an execute it from there. 但是只有在将其分配给变量并从那里执行时,我才会收到错误消息。
I need the command in the variable for my needs, as I am try to receive the command as a argument to the shell script. 我需要变量中的命令来满足我的需要,因为我试图将命令作为外壳脚本的参数来接收。
Snippet of data.xml: data.xml代码段:
<?xml version="1.0" ?>
<Settings Version="1.0.0">
<Android>
<PromptOnUpdate>true</PromptOnUpdate>
</Android>
</Settings>
Thanks for looking into this! 感谢您查看这个!
PS: I am on Mac OSX Mavericks PS:我在Mac OSX Mavericks上
Quotes aren't processed after expanding a variable. 扩展变量后不处理引号。 You need to use eval
: 您需要使用eval
:
eval "$sedcmd1"
The shell processes quotes before it expands variables. Shell在扩展变量之前先处理引号。 That means that the quotes inside your variable have no magic; 这意味着变量内的引号没有任何魔力。 they are treated the same as any other character. 它们与其他任何字符一样对待。
To store a complex command as a variable, you need an array: 要将复杂的命令存储为变量,您需要一个数组:
sedcmd1=(sed -i '' '/<PromptOnUpdate>true<\/PromptOnUpdate>/G' data.xml)
The array can be executed: 该数组可以执行:
${sedcmd1[@]}
If you are unsure if you have defined your array character, you can always see what is in it using the declare
command; 如果不确定是否定义了数组字符,则始终可以使用declare
命令查看其中的内容;
declare -p sedcmd1
which yields: 产生:
declare -a sedcmd1='([0]="sed" [1]="-i" [2]="" [3]="/<PromptOnUpdate>true<\\/PromptOnUpdate>/G" [4]="data.xml")'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.