Home > front end >  What does `;` and `&&` do to variable assignment expressions in Bash?
What does `;` and `&&` do to variable assignment expressions in Bash?

Time:07-26

I am pretty confused about below experiment results here and want to understand it better:

  1.  root@localhost$ TEST=test env | grep test
     TEST=test
    
  2.  root@localhost$ TEST=test && echo ${TEST}
     test
     root@localhost$ TEST=test; echo ${TEST}
     test
    
  3.  root@localhost$ TEST=test && env | grep test
     root@localhost$ TEST=test; env | grep test
    
  4.  root@localhost$ TEST=test && TEST=${TEST} env | grep test
     TEST=test
     root@localhost$ TEST=test; TEST=${TEST} env | grep test
     TEST=test
    
  5.  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 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,

  1. You set env var TEST for the command.
  2. You set shell var TEST.
  3. You set shell var TEST.
  4. You set shell var TEST. Then you set env var TEST for the command.
  5. You env shell var 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.

  • Related