environment variable vs shell variable — part I

Diane Khambu
2 min readJan 6, 2020
Photo by David Clode on Unsplash

Have added variables of the form KEY=value pair in.bash_profile in linux or to PATH environment variable in windows. Maybe in midst of getting things done, hadn’t deep dived/forgotten? into some common built-in bash commands. So this article is going to devote time for them with simple explanation and examples.

0. export

This bash command makes a variable be inherited by any child shells or processes from the current shell. Try the following command in your terminal.

$ HOLIDAY=candy-cane
$ echo $HOLIDAY # prints candy-cane

Now open a child shell using bash command and check if you can find value of HOLIDAY.

$ bash # open a child shell
bash-3.2$ echo $HOLIDAY
bash-3.2$

You see that nothing is printed. The child shell knows nothing about HOLIDAY key. This is because right now HOLIDAY is a shell variable. Shell variables are variables that are contained exclusively within the shell in which they are defined.

Now let’s exit out of the child shell, export the variable and re-enter into child shell. Check if you can find value of HOLIDAY.

bash-3.2$ exit
$ export HOLIDAY # exported HOLIDAY key
$bash
bash-3.2$ echo $HOLIDAY
candy-cane
bash-3.2$

You see that value of HOLIDAY is printed. This is because HOLIDAY is now an environment variable because we used export command to it. Environment variables are variables that are defined for the current shell and are inherited by any child shells or processes.

To see list of all shell variables and environment variables and their quirks, there are command for that such as printenv, env, set which is a following article.

Hope this helps you to understand difference between shell and environment variable. If you liked the article please 👏 or/and 🔗to your audience.

Thank you for reading this far!

References: digitalocean

--

--