How to Correctly Use Environment Variables on the Command Line
I always forget about how to use shell environment variable correctly. I think because I did not grasp the key concept. For example, here is the wrong approach:
|
|
The correct answer I was hoping for is:
|
|
Because what I frequently do is use environment variable inside shell script:
|
|
then do:
|
|
This works as expected because the environment variables are passed into the subshell that executing the script.
But why not the first or the wrong approach?
The reason is that shell expands the variable before the command being executed. To shell, the first approach looks like:
|
|
The environment variables FOO
and BAR
were expanded before the command was executed. Hence, no values were printed.