views:

2479

answers:

6

What is export for? What is the difference between:

export name=value

and

name=value
+2  A: 

export will make the variable available to all shells forked from the current shell.

John T
+7  A: 

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.

Brian Agnew
Specifically export makes the variable available to child processes via the environment.
Beano
+6  A: 

To illustrate what the other answers are saying:

al$ foo="Hello, World"
al$ echo $foo
Hello, World
al$ bar="Goodbye"
al$ export foo
al$ bash
bash-3.2$ echo $foo
Hello, World
bash-3.2$ echo $bar

bash-3.2$
alxp
+3  A: 

Others have answered that export makes the variable available to subshells, and that is correct but merely a side effect. When you export a variable, it puts that variable in the environment of the current shell (ie the shell calls putenv(3) or setenv(3)). The environment of a process is inherited across exec, making the variable visible in subshells.

William Pursell
A: 

Yeah, export actually makes environment variables available to all subprocesses; subshells are just one subtype of subprocesses. Not to subvert the conversation. XD

tex
A: 

Here's yet another example:

VARTEST="value of VARTEST" 
#export VARTEST="value of VARTEST" 
sudo env | grep -i vartest 
sudo echo ${SUDO_USER} ${SUDO_UID}:${SUDO_GID} "${VARTEST}" 
sudo bash -c 'echo ${SUDO_USER} ${SUDO_UID}:${SUDO_GID} "${VARTEST}"'

Only by using export VARTEST the value of VARTEST is available in sudo bash -c '...'!

For further examples see: