You're doing it correctly, but the bash syntax is easy to misinterpret: you could think that echo $TEST causes echo to fetch TEST env var then print it, it does not. Instead the shell parses the whole command line and executes all variable substitutions; THEN it creates the temp vars (TEST in your case), THEN executesSo given
export TEST=123
then
TEST=456 echo $TEST
involves the command that comes after, with those vars in its env.following sequence:
The shell parses the whole command line and executes all variable substitutions, so the command line becomes
TEST=456 echo 123It creates the temp vars set before the command, so it saves the current value of
TESTand overwrites it with 456; the command line is nowecho 123It executes the remaining command, which in this case prints 123 to stdout (so shell command that remains didn't even use the temp value of
TEST)It restores the value of
TEST
Try thisUse printenv instead, as it does not involve variable substitution:
>> export TEST=123
>> printenv TEST
123
>> TEST=456 printenv TEST
456
>> printenv TEST && TEST=456 printenv TEST && TEST=789 printenv TEST && printenv TEST
123
456
789
123
>>