Home » Linux » Shell » Bash Set Export Environmental Variable

Bash Scripts Set Environmental Variables with EXPORT [HowTo]

This tutorial will show you how to set environmental variables in Bash/Shell scripts using the export keyword.

Generally, variables declared in Bash/Shell scripts exist only within the scope of that running Bash/Shell script.

To make them available elsewhere, they can be set as an environmental variable – meaning that the variable will be available when executing commands outside of the script on your system – for example, making the variable available from the command line after the script has completed.

The export keyword does this – here’s how to use it.

What is an Environmental Variable

An environmental variable works much like any other variable, but it’s available everywhere – inside scripts, on the command line, and to other running programs.

Your system already has many environmental variables defined – for example, your home directory is available by reading the environmental variable $HOME.

You can view all currently set environmental variables with the env command:

env

Set Environmental Variables with export

The following script, testScript.sh, sets an environmental variable and then exits:

#!/bin/bash
export MY_ENV_VAR="Save the environment!"

Now, when the above script is executed:

sh ./testScript.sh

The variable MY_ENV_VAR is available after it has been completed. This can be confirmed by running:

echo $MY_ENV_VAR

The environmental variable has been set and is now available across the system.

The printenv command can also be used to view an environmental variable

printenv MY_ENV_VAR

Persisting After Reboot

Environmental variables set with export will not persist a reboot of your computer. To permanently set an environmental variable, it must be declared in your ~/.bashrc file.

The ~/.bashrc file is a script that is run each time you log in. By adding your export statements to it, your environmental variables will be added for each session you log in to.

nano ~/.bashrc

Above, the nano text editor is used to edit the file. Add your export statements to the end of the file, and they’ll be there after you reboot:

export MY_ENV_VAR="Save the environment!"

System-Wide Environmental Variables

These environmental variables will only be there for the current user. If you’re an administrator and you want to make them available to all users and processes, add the lines to the /etc/environment file instead:

sudo nano /etc/environment

 

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment