2

This echo call outputs the variable:

$ FOO="bar" eval 'echo foo: "$FOO"'
foo: bar

But this one does not:

$ FOO="bar" echo foo: "$FOO"
foo:

Why is that? I'm pretty sure I have the single and double quotes right.

Environment-wise, I'm on a MacBook Pro using iTerm2 with a current version of bash:

$ echo $BASH_VERSION
4.4.23(1)-release
jlucktay
  • 390
  • 1
  • 7
  • 23
  • 1
    See [Bash Reference Manual: Simple Command Expansion](https://www.gnu.org/software/bash/manual/bash.html#Simple-Command-Expansion). Without a semi-colon, you are executing `echo` with `$FOO` added to its environment. – PesaThe Jul 09 '18 at 08:40

1 Answers1

-2

This is happening because in your second example, $FOO is being expanded before the line is evaluated.

EDIT: This works if the second part is in a separate script:

$ cat foo.sh
echo foo: "$FOO"

$ FOO="bar" ./foo.sh
foo: bar

Or:

FOO="bar" bash -c 'echo $FOO'

Having the command in single quotes means it isn't expanded first by the shell.

Alex Stiff
  • 844
  • 5
  • 12