开发者

order of expansion between variable expansion and command substitution

开发者 https://www.devze.com 2023-03-24 07:32 出处:网络
The bash man says that variable expansion occurs before command substitution. I was seeking of an example that shows it clearly. So i tried this:

The bash man says that variable expansion occurs before command substitution. I was seeking of an example that shows it clearly. So i tried this:

roo开发者_开发知识库t@antec:/# var=1 
root@antec:/# echo $(var=2; echo $var)
2
root@antec:/#

I was expecting bash to do:

1) replace $var by "1" in the substitution

2) execute echo $(var=2; echo 1)

Obviously this is not what bash is doing ..

Can someone please explain what is going one here ? And if someone has an example showing the precedence of variable expansion over command substitution it would be nice too


I do not know what the bash man page is talking about.

The POSIX specification for the shell says:

The order of word expansion shall be as follows:

  1. Tilde expansion, parameter expansion, command substitution, and arithmetic expansion shall be performed, beginning to end.
  2. Field splitting shall be performed on the portions of the fields generated by step 1, unless IFS is null.
  3. Pathname expansion shall be performed, unless set -f is in effect.
  4. Quote removal shall always be performed last.

This makes it pretty clear that variable expansion (aka. "parameter expansion") happens at the same time as command expansion ("command substitution"), not before or after.

So I do not think the example you are asking for exists.


What is happening:

a) The $() expression is executed b) Variables in var=2 are substituted c) var=2 is executed d) Variables in echo $var are substituted e) echo 2 is executed

I think a good example of variable expansion first is:

foo=echo; echo $($foo)


I think your confusion here is that you think the variable expansion happens inside a command substitution, when it doesn't.

Actually, bash will only do a command substitution there, where the command is var=2; echo $var. That will then be run in a subshell, which will execute the command, doing all expansion passes yet again for each command run.


In newer bash man pages, they put semicolons to indicate the precedence:

The order of expansions is: brace expansion ; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion) ; word splitting ; and pathname expansion.

And from the code you can see that a $ triggers the param_expand function, which will do command substitution or variable expansion if the next character is a parenthesis or a name respectively. It will not do an additional variable expansion in command_substitute.

0

精彩评论

暂无评论...
验证码 换一张
取 消