A comprehensive guide on the export command and its usage to export variables to child processes.

The export command plays a crucial role in exporting variables to child processes. But what does this actually mean? Let’s dive deeper into it.

Imagine you have a variable named TEST defined as follows:

TEST="test"

To check the value of this variable, you can simply use the echo $TEST command. However, if you try to define a Bash script in a file named script.sh with the above command, and then run the script using chmod u+x script.sh and ./script.sh, you will notice that the echo $TEST line does not print anything.

This happens because in Bash, the TEST variable is defined locally to the shell. When you execute a shell script or another command, a subshell is launched to execute it, which does not inherit the local variables of the current shell.

To make the variable accessible in the subshell, you need to define it using the export command as follows:

export TEST="test"

Now, if you run ./script.sh again, it will print “test” as expected.

In some cases, you may need to append something to a variable, such as the PATH variable. You can achieve this by using the following syntax:

export PATH=$PATH:/new/path

Using the export command is a common practice when creating new variables in this manner. Additionally, it is used when defining variables in the .bash_profile or .bashrc configuration files with Bash, or in the .zshenv file with Zsh.

To remove a variable, you can utilize the -n option like this:

export -n TEST

If you call the export command without any option, it will list all the exported variables.

The export command is not limited to Linux. It works seamlessly on macOS, WSL (Windows Subsystem for Linux), and anywhere you have a UNIX environment.

Tags: Linux commands, export, variable, subshell, shell script, environment