Why ‘export’ if i could just direct assign the variables in bash?

January 25th, 2011 mysurface Posted in Bash, export | Hits: 133278 | 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.

8 Responses to “Why ‘export’ if i could just direct assign the variables in bash?”

  1. Really good…

    nice example….

    Thanks a lot

  2. That was a good example and explanation! :)

  3. just cant understand linuxxx so complicated

  4. 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!

  5. 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.

  6. Really nice example. helped a lot..

  7. 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!!

  8. 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.

Leave a Reply