I am pretty confused about below experiment results here and want to understand it better:
root@localhost$ TEST=test env | grep test
TEST=test
root@localhost$ TEST=test && echo ${TEST}
test
root@localhost$ TEST=test; echo ${TEST}
test
root@localhost$ TEST=test && env | grep test
root@localhost$ TEST=test; env | grep test
root@localhost$ TEST=test && TEST=${TEST} env | grep test
TEST=test
root@localhost$ TEST=test; TEST=${TEST} env | grep test
TEST=test
root@localhost$ export TEST=test && TEST=${TEST} env | grep test; unset TEST
TEST=test
root@localhost$ export TEST=test; TEST=${TEST} env | grep test; unset TEST
TEST=test
My main confusion being that:
Why does not #3 work?
Why does #4 work?
There are two types of vars: Environment (exported) vars, and shell vars.
VAR=val
sets the env var named VAR
if it already exists.VAR=val
sets the shell var named VAR
if env var VAR
doesn't exist.VAR=val cmd
sets the env var named VAR
for cmd
only.The env vars are provided to child processes as their environment.
Shell vars, on the other hand, exist only within that shell process. Child processes have no access to them.
So,
TEST
for the command.TEST
.TEST
.TEST
. Then you set env var TEST
for the command.TEST
. Then you set env var TEST
for the command.Why does #4 work?
You set an env var.
Why does not #3 work?
You did not set any env vars.