2

I've noticed something odd in bash. Let's suppose I have a file toto containing the following :

#!/bin/bash
export foo=2

if I run source toto; echo foo=$foo , I get as expected

foo=2

However, if I run bash -c "source toto; echo foo=$foo", I get

foo=

Same thing if I run

bash << EOF
source toto
echo foo=$foo
EOF

Still, If I create a file test.sh containing:

#!/bin/bash
echo foo=$foo

And then I run bash -c "source toto; ./test.sh" then I finally get the expected

foo=2

Does someone understand these results? Thanks!

1 Answers1

7

When you run

bash -c "source toto; echo foo=$foo"

the shell you're typing into expands all the variables in the string. At that time, $foo doesn't yet have a value, so it's as if you'd written

bash -c "source toto; echo foo="

If you use single quotes instead of double quotes, variables are not expanded. Then the literal command line is sent to bash, and it will expand $foo itself.

bash -c 'source toto; echo foo=$foo'

See Difference between single and double quotes in Bash

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612