Why ‘export’ if i could just direct assign the variables in bash?
January 25th, 2011 mysurface Posted in Bash, export | Hits: 92691 | 5 Comments »
I can direct assign value to a variable in my bash shell why I still need the command ‘export’ ? What is the different between them?
If you have doubts about this, please continue to read on it.
Lets do an experiment in a bash shell:
$ HELLO=world
$ export HELLO2=world2
$ echo $HELLO $HELLO2
world world2
Hey, it works exactly the same!
Not really exactly the same if you use it in your bash script. Let me show you an example. Let say I have a bash script main.sh , which it calls child.sh.
child.sh
#!/bin/bash
echo $HELLO $HELLO2
main.sh
#!/bin/bash
HELLO=world
export HELLO2=world2
./child.sh
Now lets execute ./main.sh
$ ./main.sh
world2
Hey! the ‘world’ has gone!
When we assign the variable directly, we make the variable local, when we call a child script, the local variable will not available for the child script. In contrast, if we export the variable, we make it appear as an environment variable, which it will be available globally within that bash session. That is the reason, child.sh reads $HELLO2 but not $HELLO.







January 25th, 2011 at 2:14 am
Really good…
nice example….
Thanks a lot
January 27th, 2011 at 12:56 am
That was a good example and explanation! :)
March 11th, 2011 at 1:40 pm
just cant understand linuxxx so complicated
March 16th, 2011 at 8:45 am
Hey thanks for this post.
I was wondering if when you use export does the exported variable stays global forever or it is lost after closing the terminal?
Thanks!
September 12th, 2011 at 6:31 pm
andreson: variables are never passed “out” of shells, so yes it is lost if you close the terminal (ie. exit your shell process). You can see the process more clearly like this: start a terminal, then do:
$ export HELLO=world
$ bash
# this starts a sub-shell, just as if you’d entered a script
$ echo $HELLO
world
$ HELLO=goodbye
$ echo $HELLO
goodbye
# now we exit the sub-shell
$ exit
# back in the main shell
$ echo $HELLO
world
exiting this shell again, and $HELLO is lost.