Bash – Why doesn’t source work when I call bash -c

bashquotingshell

I want to run a command that sources a script to take on some env. variables before executing, without sourcing them in my current shell.

test.env

export test=1

None of these commands echo the env. variable:

a) Shouldn't this work? Aren't I just executing these commands in a new shell and returning the output?

$ bash -c "source test.env && echo $test"

b) Here I execute test.env and try to run echo $test in the same process using exec.

$ bash -c "./test.env && exec echo $test"

c) Lastly I just tried this since it was a possible permutation. But it executes test.env and the echo command as separate processes.

$ bash -c "./test.env && echo $test"

And how can I get this to work where the env. variables are sourced before the 2nd command is executed?

Best Answer

You must escape dollar sign $ in your first command, otherwise bash will expand it before your command executed:

$ bash -c "source test.env && echo \$test"

Or you should use single quote instead of double quote:

$ bash -c 'source test.env && echo $test'