Hello again, today we are discussing exporting a variable in a UNIX Shell. I am sure that sometimes, you have come across something like the following code snippet:
debug=true
or:
export debug=true
In both cases, we are assigning the value of true to a variable named debug. But what does this mystical export statement do?Exporting a variable in a Shell it simply means that the variable is available to its children. Let’s put the word into actions, on any UNIX/Linux systems, open a Shell of your choice. To simplify the test, we assume that we are operating within a bash shell. Once you get the $ prompt, type the following command and press the Enter key:
debug=true
The above statement simple assigns the value of true to a variable named debug. Now type the following command and press the Enter key:
echo $debug
If all goes well, you will simply see the output of the command to be true, which is the value of the variable. At this point, to verify that the children shells will not inherit the variable, let’s open a child shell with the following command followed by the Enter key:
bash
If all goes well, you will simply see another $ prompt, now type the same command as above, followed by the Enter key:
echo $debug
And just like we predicted, the command produces no output, meaning that the variable debug is only set for the parent shell and not inherited by the children shells. Now, let’s exit from the current shell by typing the following command:
exit
At this point, you simply return to the parent shell. Let’s now verify that exporting the variable debug will make the variable available to the children shells. Type the following command followed by the Enter key:
export debug=true
Now, reopen a child shell with the command bash, just like before:
bash
At this point, type the same command we typed before followed by the Enter key:
echo $debug
And just like we predicted, the value of true is displayed by the command.
At this point, you are probably asking yourself, when would I use export and when would I not use it?
The answer is “it depends” on the software or script you are developing, if you need the variable not to propagate to children, you would not export it, and if you do, you will export it. The more you develop scripts in a Shell and the more you will understand when and why you would use the export statement.
I hope that, at the very least, you know about the export statement, and your development experience will improve.
Thank you for reading and type away…