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
touch parent.sh child.shchmod a+x parent.sh child.shWhenever 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.
SHARABLE_ENV="Hello, World!"# This variable is only available in the current shell sessionecho "Current shell: $SHARABLE_ENV"# If you spawn a child process, it won't have access to SHARABLE_ENV./child.shecho "Child shell": $SHARABLE_ENVRunning the parent file parent.sh
./parent.shOutput
Current shell: Hello, World!Child shellAs 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
export SHARABLE_ENV="Hello, World!"# This variable is available in the parent and child processecho "Current shell: $SHARABLE_ENV"# If you spawn a child process, it will have access to SHARABLE_ENV./child.shRunning the parent file parent.sh again with export added.
./parent.shOutput
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.