When is variable in backticks expanded using Bash

2019-07-27 09:24发布

If I have a variable in backticks is it expanded in the shell or in the subshell? For example:

FOO=BAR
BAZ=`[[ $FOO == BAR ]] && echo 1 || echo 0`

Is it defined when $FOO is expanded? For example does the subshell see this:

[[ $FOO == BAR ]] && echo 1 || echo 0

or this:

[[ BAR == BAR ]] && echo 1 || echo 0

1条回答
Deceive 欺骗
2楼-- · 2019-07-27 10:15

(You should really use $(...) instead of backticks. But the principle is the same.)

The command to be executed in the subshell consists of the literal characters inside the command substitution form, except for the idiosyncratic and sometimes confusing rules around backslashes inside backticks. So the variable expansion happens inside the subshell.

For example,

x=$(foo=bar && echo $foo)

will define x=bar but will not result in foo being (re-)defined in the outer shell.

查看更多
登录 后发表回答