Programming
linux bash shell
Updated Fri, 20 May 2022 22:18:54 GMT

Defining a variable with or without export


What is export for?

What is the difference between:

export name=value

and

name=value



Solution

export makes the variable available to sub-processes.

That is,

export name=value

means that the variable name is available to any process you run from that shell process. If you want a process to make use of this variable, use export, and run the process from that shell.

name=value

means the variable scope is restricted to the shell, and is not available to any other process. You would use this for (say) loop variables, temporary variables etc.

It's important to note that exporting a variable doesn't make it available to parent processes. That is, specifying and exporting a variable in a spawned process doesn't make it available in the process that launched it.





Comments (5)

  • +0 – Specifically export makes the variable available to child processes via the environment. — Jul 21, 2009 at 13:35  
  • +0 – I'd also add that if the export is in a file that you "source" (like . filename) then it exports it to your working environment as well. — Sep 17, 2013 at 22:44  
  • +9 – @rogerdpack can't you do that without export? cat > blah \n a=hi \n . blah; echo $a; outputs 'hi' for me. — Sep 30, 2013 at 23:49  
  • +3 – Nice it does work even without the export. So I guess when sourcing a file, if you use export it will be reflected in child processes, if you don't it will just affect the local bash environment... — Oct 01, 2013 at 15:01  
  • +0 – There's one edge-case to this; name=value command does make the variable available in the sub-process command. — Dec 23, 2015 at 11:09