Defining a variable with or without export

后端 未结 14 1660
借酒劲吻你
借酒劲吻你 2020-11-22 09:58

What is export for?

What is the difference between:

export name=value

and

name=value
14条回答
  •  轮回少年
    2020-11-22 10:38

    export NAME=value for settings and variables that have meaning to a subprocess.

    NAME=value for temporary or loop variables private to the current shell process.

    In more detail, export marks the variable name in the environment that copies to a subprocesses and their subprocesses upon creation. No name or value is ever copied back from the subprocess.

    • A common error is to place a space around the equal sign:

      $ export FOO = "bar"  
      bash: export: `=': not a valid identifier
      
    • Only the exported variable (B) is seen by the subprocess:

      $ A="Alice"; export B="Bob"; echo "echo A is \$A. B is \$B" | bash
      A is . B is Bob
      
    • Changes in the subprocess do not change the main shell:

      $ export B="Bob"; echo 'B="Banana"' | bash; echo $B
      Bob
      
    • Variables marked for export have values copied when the subprocess is created:

      $ export B="Bob"; echo '(sleep 30; echo "Subprocess 1 has B=$B")' | bash &
      [1] 3306
      $ B="Banana"; echo '(sleep 30; echo "Subprocess 2 has B=$B")' | bash 
      Subprocess 1 has B=Bob
      Subprocess 2 has B=Banana
      [1]+  Done         echo '(sleep 30; echo "Subprocess 1 has B=$B")' | bash
      
    • Only exported variables become part of the environment (man environ):

       $ ALICE="Alice"; export BOB="Bob"; env | grep "ALICE\|BOB"
       BOB=Bob
      

    So, now it should be as clear as is the summer's sun! Thanks to Brain Agnew, alexp, and William Prusell.

提交回复
热议问题