Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order of expansion between variable expansion and command substitution

Tags:

bash

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:

root@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

like image 593
user368507 Avatar asked Dec 12 '25 15:12

user368507


1 Answers

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.

like image 55
Nemo Avatar answered Dec 14 '25 08:12

Nemo