Why ‘export’ if i could just direct assign the variables in bash?
January 25th, 2011 mysurface Posted in Bash, export | Hits: 117553 | 8 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.
September 10th, 2012 at 3:29 pm
Really nice example. helped a lot..
April 10th, 2013 at 12:12 pm
Oh my goodness! Incredible article dude! Thank you so
much, However I am going through troubles with your RSS. I don’t know why I cannot subscribe to it. Is there anyone else getting the same RSS problems? Anyone that knows the solution can you kindly respond? Thanx!!
May 29th, 2013 at 11:39 am
Because of this it is also one of the most expensive so
getting a rebate helps keep the cost down.
That tooth brush is an “Oral B Pulsar Soft” toothbrush.
Long life rechargeable batteries – A properly charged battery can serve for a whole month without requiring further charging.