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

2020-02-06 17:03发布

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?

2条回答
相关推荐>>
2楼-- · 2020-02-06 17:36

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"
查看更多
\"骚年 ilove
3楼-- · 2020-02-06 17:43

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.

查看更多
登录 后发表回答