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.
#!/bin/bash echo $HELLO $HELLO2
#!/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.