简体   繁体   中英

Bash parameter substitution

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.

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.

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!!

PS

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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