Bash parameter substitution

好久不见. 提交于 2019-12-11 07:39:10

问题


I am trying to learn bash parameter substitution and have a very basic question:

Why does this work:

#!/bin/sh
v1="-E"
v2="s/./x/g"
sed "$v1" "$v2" <<<"abc" # result = "xxx"

but this doesn't work:

#!/bin/sh
v1="-E"
v2="s/./x/g"
sed "$v1 $v2" <<<"abc" # result = "sed: illegal option..."

I am using Mac OS X bash.


回答1:


Because on the second example, (the wrong one) you are using the quotes wrong. The quotes are being used in order to specify that what whatever comes out of that variable has to be treated as a string, and you added two variables in one of them. each one has to be seperated, because like this its like saying its one variable, so sed sees one variable not two. So for example, lets say:

v1=123
v2=456

as you have it on the second example, sed will see this: "123456", though what you want sed to see is two variables, one to have 123 and the second one to have 456. Thats why you should have them in seperated quotes! I hope i explained it good enough for you to understand!!

P.S

What you actually did on the second example, you could use it at some point if you want to concutenate two variables, and add them in another as a string :)

UPDATE

So lets have an example here.....

v1=123
v2=456
CASE1="$v1" "$v2"
CASE2="$v1 $v2"
echo CASE1
echo CASE2

For the CASE1 the output would be 123456, as for the CASE2 the output would be 123 456..... Do you get the difference now? The only way to do it in both ways and print out the same thing would be this.....

v1=123
v2=456
CASE1="$v1" "$v2"
CASE2="$v1$v2"

having the case2 WITHOUT a space between the variables...




回答2:


The problem in your second example is that double quotes protect enclosed whitespace from word splitting in Bash:

Instead of two arguments -E and s/./x/g, only one single argument -E s/./x/g (containing a blank) will be passed to the respective exec() system call and finally to sed in that case.



来源:https://stackoverflow.com/questions/36938295/bash-parameter-substitution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!