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?
CodePudding user response:
There are two types of vars: Environment (exported) vars, and shell vars.
VAR=val
sets the env var namedVAR
if it already exists.VAR=val
sets the shell var namedVAR
if env varVAR
doesn't exist.VAR=val cmd
sets the env var namedVAR
forcmd
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,
- You set env var
TEST
for the command. - You set shell var
TEST
. - You set shell var
TEST
. - You set shell var
TEST
. Then you set env varTEST
for the command. - You env shell var
TEST
. Then you set env varTEST
for the command.
Why does #4 work?
You set an env var.
Why does not #3 work?
You did not set any env vars.