Export your variables with caution

Table of Contents

Omitting “export” to share the variable

We’ll start by creating two files parent.sh and child.sh

terminal - bash console
touch parent.sh child.sh
chmod a+x parent.sh child.sh

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 your child processes.

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 SHARABLE_ENV
./child.sh
child.sh
echo "Child shell": $SHARABLE_ENV

Running the parent file parent.sh

terminal - bash console
./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.

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

Why does this happen?

Bash (and most shells) distinguish between shell variables and environment variables:

Shell variables live only in the current shell session. They are not passed to subprocesses.

Environment variables are explicitly marked with export. When you export a variable, Bash adds it to the process’s environment table. This table is then copied over whenever a new child process is forked.

In other words:

MY_VAR=value → only visible to the current shell.

export MY_VAR=value → visible to the current shell and all child processes spawned from it.

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.

My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts