PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 19, 2022

[FIXED] What does `;` and `&&` do to variable assignment expressions in Bash?

 August 19, 2022     bash, environment, environment-variables, shell     No comments   

Issue

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?


Solution

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.



Answered By - ikegami
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,205,317

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing