Omitting export to share the variable

Whenever we export the variables we may have to be extra careful. Imagine a scenario where you want to spin up multiple processes from your current process and you expect the environment variables to be accessible by you child processes.

We start by creating two files parent.sh & child.sh

parent.sh

# parent.sh
SHARABLE_ENV="Hello, World!"
# This variable is only available in the current shell session
echo "Current shell: $SHARABLE_ENV"
# If you spawn a child process, it won't have access to MY_VARIABLE
./child.sh

child.sh

echo "Child shell": $SHARABLE_ENV

Running the parent file parent.sh

$ bash parent.sh

Output

Current shell: Hello, World!
Child shell

As you can see the child process loses the reference to the environment variable that was supposed to be passed by the parent.

Using export to share the variable

Now we modify the parent.sh file to export the variable

parent.sh

# parent.sh
export SHARABLE_ENV="Hello, World!"
# This variable is available in the parent and child process
echo "Current shell: $SHARABLE_ENV"
# If you spawn a child process, it will have access to SHARABLE_ENV
./child.sh

Running the parent file parent.sh again with export added.

$ bash parent.sh

Output

Current shell: Hello, World!
Child shell: Hello, World!

As you can see the child process now has access to the environment variable that was “exported” by the parent.

So should I always export my environment variables?

  • If you are dealing with variables that needs to be accessed by the child processes, you have to export them.
  • There might be scenarios where you’d want to keep your variables secret and not pass it down to child processes, in such cases you have to omit using the export keyword.

Bottomline is to keep an extra eye on the export keyword whenever forking is involved. Although the example demonstrated here is for bash, you can replicate the same scenario in any general purpose programming language.