In Bash, why `x=100 echo $x` doesn't print any

2020-02-06 17:05发布

问题:

I saw codes like this:

fqdn='computer1.daveeddy.com'

IFS=. read hostname domain tld <<< "$fqdn"
echo "$hostname is in $domain.$tld"
# => "computer1 is in daveeddy.com"

I think it works because IFS is assigned to . in the third line.. So I tried this:

x=100  echo $x

but found the bash doesn't print anything, while I expect it will print 100..

Moreover, I found x=100 echo $x; echo $x print nothing, while x=100; echo $x prints 100, which is very confusing.

Does anyone have ideas about this?

回答1:

The $x is expanded before echo runs, and the result is passed to echo as an argument. echo does not use the value of x in its environment.

In the first example, read uses the value of IFS in its environment to split the string it receives via the here string.



回答2:

here is another way to think about it:

$ a="echo 100" $a

This is equal to:

$ a="echo 100"    

Because at the time of scanning the line, $a is empty. Variable substition occurs first, so the $a just disappears.

Compare this to a very similar statment:

$ a="echo 100"; $a   # returns "100"