Search code examples
bashshellbackticks

When is variable in backticks expanded using Bash shell?


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

Solution

  • (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.