Bash where to set environment variables?
There’s more than one type of environment variable on Linux. Learn how to see them, create them for local and remote logins, and make them survive reboots.
When you launch a terminal window and the shell inside it, a collection of variables is referenced to ensure the shell is configured correctly. These variables also ensure that any information to which the terminal window and shell might need to refer is available. Collectively, these variables hold settings that define the environment you find inside your terminal window, right down to the look of the command prompt. So, naturally, they’re referred to as environment variables.
Some environment variables are system-wide, or global. Others are session-wide and can only be seen by you. Others can’t reference your session environment variables. There’s a third set of environment variables defined within the shell. Your locale, time zone, and keyboard settings, the set of directories searched when the shell tries to find a command, and your default editor, are all stored in shell environment variables.
We’re going to show you how to see the environment variables that exist on your system, and we’ll describe how to create your own. We’ll also show you how to make them available to child processes and to be persistent across reboots.
When a shell starts, it goes through an initialization phase. It’s at this point that it reads the environment variables that define the environment of the shell.
When a program or command is launched from that shell—known as a child process—it inherits the environment of the parent process—but watch out! As we’ll see, you can create variables that don’t get added to your environment, so they won’t be inherited by a child process.
If the child process is a shell, that shell will initialize from its own, fresh, set of variables. So, if you alter the command prompt in the current shell, and then launch a child shell, the child shell won’t inherit the modified command prompt of the parent.
By convention, environment variables are given uppercase names. Here are some of the global environment variables, and what the values they contain represent:
RELATED: How to Use pushd and popd on Linux
We can see what some of these are set to using nothing more sophisticated than echo, which will write the values to the terminal window. To see the value held by an environment variable, you need to add a dollar sign ($) to the start of its name.
A nice touch is that you can use tab completion to fill in the environment variable name for you. Type a few letters of the name and hit Tab. The name of the variable is completed by the shell. If that doesn’t happen, you’ll need to type a few more letters to distinguish the environment variable from other commands with names that start with those same letters:
To create your own global environment variables, add them to the /etc/environment file. You’ll need to use sudo to edit this file:
To add an environment variable, type its name, an equal sign (=), and the value you want the environment variable to hold. Don’t space before or after the equal sign (=). The name of the environment variable can contain letters, an underscore (_), or numbers. However, the first character of a name cannot be a number.
If there are spaces in the value, be sure you enclose the entire value in quotation marks (").
Save the file, and then log out and back in again. Use echo to test that a new variable exists and holds the value you set:
Because it’s a global environmental variable, and available to everyone, user mary can reference the environment variable when she next logs in:
To see all the environment variables at once, type printenv. There’s a lot of output, so it makes sense to pipe it through sort, and then into less:
The sorted list of environment variables is displayed for us in less.
We can pipe the output through grep to look for environment variables related to a particular topic.
RELATED: How to Edit Text Files Graphically on Linux With gedit
These are some of the shell environment variables used in bash to dictate or record its behavior and functionality. Some of the values are updated as you use the terminal. For example, the COLUMNS environment variable will be updated to reflect changes you might make to the width of the terminal window:
RELATED: How to Use pushd and popd on Linux
Let’s check a few of these shell variables:
For the sake of completeness, here are the tokens you can use in the command prompt definitions:
You’ll find the definition of your PS1 environment variable in your .bashrc file.
To create environment variables for your own use, add them to the bottom of your .bashrc file. If you want to have the environment variables available to remote sessions, such as SSH connections, you’ll need to add them to your .bash_profile file, as well.
The format of the environment variable definition is the same for both files. To add a definition to your .bash_profile file, type this in your home directory:
We’ve added an environment variable called INHERITED_VAR. Note the word “export” at the start of the line.
Save and close your file after you finish editing. You could log out and back in again, or you can cause the shell to re-read the .bash_profile file using the dot command (.) like this:
Now, let’s create an environment variable on the command line:
If we use echo, we can see that both environment variables are accessible to us:
You’ll notice the definition of the INHERITED_VAR environment variable had the word “export” at the start of the line. This means the environment variable will be inherited by child processes of the current shell. If we launch another one using the bash command, we can check the two variables again, from inside the child shell:
As you can see, the INHERITED_VAR is accessible in the child shell, but LOCAL_VAR is not. We simply get a blank line.
Although “export” adds the environment variable part to the environment that child processes inherit, INHERITED_VAR is not a global environment variable. For example, user mary cannot reference it:
To close our child bash session, we use exit:
Inherited environments affect scripts, too. Here’s a simple script that writes the values of our three environment variables to the terminal window:
This was saved to a file called envtest.sh, and then made executable with the following:
When we run the script, it can access two out of three environment variables:
The script can see the WEBSITE global environment variable and the INHERITED_VAR exported environment variable. It cannot access LOCAL_VAR, even though the script is running in the same shell where the variable was created.
If we need to, we can export an environment variable from the command line. We’ll do that to our LOCAL_VAR, and then run the script again:
The environment variable has been added to the environment of the current shell, and so it appears in the environment that is inherited by the script. The script can reference that environment variable, too.
Global environment variables are accessible to remote login sessions, but if you want your locally defined environment variables available to you remotely, you must add them to your .bash_profile file. You can set the same environment variable in the .bashrc and .bash_profile files, with different values. This could be picked up by a script, say, to modify its behavior for people using the system locally or remotely.
(At the risk of confusing matters, there’s also a .profile file. It can hold environment variable definitions, too. However, the .profile file is not read if the .bash_profile file is present. So, the safest thing to do—and the bash-compliant way—is to use the .bash_profile file.)
To edit the .bash_profile file, we’ll use gedit again:
We’re going to add the same environment variable with the same value we used before.
Save your changes and close gedit.
On another computer, we’ll make an SSH connection to the test computer.
Once we’re connected, we’ll run the script once more:
The .bash_profile file has been read as part of the initialization of the remote login, and the INHERITED_VAR environment variable is accessible to us and the script.
To unset an environment variable use the unset command. If we unset the global environment variable, WEBSITE, and the exported environment variable, INHERITED_VAR, they’ll no longer be available on the command line, nor in child processes:
A point to note is this only changes the availability of global environment variables for you in this session. Another person who’s logged in simultaneously will still be able to access his instance of that global environment variable. His instance was initialized and read from the /etc/environment file during his login process, and is independent of anyone else’s copy of the variable.
As an example, user mary can still access the WEBSITE environment variable and read its value, even though user dave has unset it in his session:
Environment variables can be used to let scripts and applications know how they should behave. They can be used to store settings or small amounts of data. For example, a script can populate an environment with a value that can be referenced by other scripts without having to write them to a file.
On computers, variables are used in a similar way.
For instance, any person with a user account on a computer has a home directory where the computer keeps their personal data. But each user has a distinct home directory (/home/seth for Seth, /home/tux for Tux, and so on for each user), so when you want to refer generically to a home directory, you could use the variable $HOME to indicate the home directory of the current user, regardless of the user's login name.
Environment variables are special variables (like $HOME) that contain information about your login session. They're stored for the system shell to use when executing commands. They exist whether you’re using Linux, Mac, or Windows. Many of these variables are set by default during installation or user creation.
While environment variables apply to all modern systems, this article specifically addresses environment variables in the Bash shell on Linux, BSD, Mac, and Cygwin.
Environment variables are no different, technically, than variables. They can be set, recalled, and cleared with exactly the same syntax used for variables. If you’re not used to using variables in Bash, read my variables in Bash article before continuing.
You don’t often use environment variables directly. They’re referenced by individual applications and daemons as needed. For instance, your home directory is set as an environment variable when you log in. For example, on Linux you can see your HOME environment variable's contents like this:
On a Mac:
On Windows:
You can view all environment variables set on your system with the env command. The list is long, so pipe the output through more to make it easier to read:
Environment variables can be useful when you want to override default settings, or when you need to manage new settings that your system has no reason to create on its own. For instance, when you type a command, the only reason your computer knows how to find the application corresponding to that command is that the PATH environment variable tells it where to look. This variable lists valid directories for your operating system to search for commands, whether that command is ls or cp, or a graphical application like Firefox or Lutris, or anything else.
Different environment variables get used by different systems. Your PATH variable is vital to your terminal emulator, for instance, but a lot less significant to, say, Java (which has its own paths, which point to important Java libraries). However, the USER variable is used by several systems as a way to identify who is requesting a service. For example, if you’re on a multiuser system and need to check your local mailbox, your mail command knows which mail spool to retrieve based on the MAIL and USER variables.
Usually, the installer program, whether it’s dnf on Fedora, apt on Ubuntu, brew on Mac, or a custom installer, updates your environment variables for a new application. Sometimes, though, when you’re installing something outside of your distribution’s intended toolset, you may have to manage an environment variable yourself. Or you might choose to add an environment variable to suit your preferences. If you decide you want to keep some applications in a bin folder located in your home directory, then you must add that directory to your PATH so your operating system knows to look there for applications to run when you issue a command.
You can add a location to your path the way you create throw-away variables. It works, but only as long as the shell you used to modify your system path remains open. For instance, open a Bash shell and modify your system path:
Confirm the result:
Close the session:
Open a new one and take a look at the PATH variable:
This variable has reverted to its default state because PATH isn’t getting set with each new shell. For that, you must configure your variables to load any time a shell is launched.
You can set your own persistent environment variables in your shell configuration file, the most common of which is ~/.bashrc. If you’re a system administrator managing several users, you can also set environment variables in a script placed in the /etc/profile.d directory.
The syntax for setting a variable by configuration file is the same as setting a variable in your shell:
Close the current shell, or else force it to load the updated config:
Finally, take another look at your system path:
It is now set correctly to include your additional custom directory.
You can create and manipulate environment variables at will, and some applications do just that. This fact means that many of your environment variables aren’t used by most of your applications, and if you add your own arbitrary variables then some could be used by nothing at all. So the question is: How do you find out which environment variables are meaningful?
The answer lies in an application’s documentation. For instance, to find out what options are available to you for your general Bash environment, you can read the Bash documentation. While the Bash man page mentions many important variables, the GNU info page for Bash features two exhaustive lists of useful Bourne Shell and Bash environment variables, and how each is used.
For example, in the info page list:
This output tells you that the HISTCONTROL environment variable controls how your Bash history is presented, and what values you can use to customize that experience. In this example, the ignoredups value tells the output of the history command to ignore duplicate lines.
You can test this one easily. First, issue the same command twice in a row:
View your history, or at least the most recent entries:
You can see that duplicate entries are indeed listed now.
Set a new environment variable in your .bashrc file based on what you read in the info page:
Save and then load your new configuration:
Issue two commands twice in a row:
Variables can be used repeatedly throughout the code or by your operating system to provide values. You can edit them, overwrite them, and delete them.
In this tutorial, I'll teach you what environment variables are and how to set them in Linux.
Environment variables are the variables specific to a certain environment. For example, each user in an operating system has its own environment. An admin user has a different environment than other users do, for example.
You might declare an environment variable only required by your user (for example a secret token) that doesn't need to be exposed to other users.
Here are some examples of environment variables in Linux:
These environment variables vary based on the current user session.
The command used to display all the environment variables defined for a current session is env.
Here is the output for my session:
There are two ways to print the already defined environment variables:
Let's print the value of the variable SHELL using both methods. Here's an example of printing using printenv:
And here's an example of using echo:
The basic syntax to define an environment variable is as follows:
Let's define an environment variable, list it, and print its value.
However, the variables defined using this method are stored for the current session only. They won't be available for the next session.
Let's verify by opening a new session and printing the variable's value.
But, we can make the definitions persistent as shown in the next section.
To make the JAVE_HOME variable persistent, edit the file .bashrc and define its value in it.
The .bashrc is a script file that's executed whenever a user logs in. It is hidden and located in the user's home directory by default.
I have edited my .bashrc file as follows:
For the changes to take effect, update the .bashrc file using the source command:
Let's verify by opening a new session.
Sometimes you might need to define a global environment variable that is accessible by all users.
For that, we need to first declare a variable and make changes in relevant files where environment variables are read from.
Let's go step by step.
2. Edit the following files:
For the changes to take effect, use the command source /etc/environment.
Time to test!
Now, I'll switch the user to the root user and verify if I can access the variable GLOBAL_VARIABLE.
It worked! I have been able to access the global variable defined by the user Zaira through the root user as well. The same would apply to other users too. So now you also know how to define global environment variables.
In this tutorial, you learned how to create and define environment variables in Linux. You also learned how to make them persistent so that you can use them across multiple sessions.
What’s your favorite thing you learned here? Let me know on Twitter!
You can read my other posts here.
You can set an environment variable permanently by placing an export command in your Bash shell's startup script " ~/.bashrc " (or "~/.bash_profile ", or " ~/.profile ") of your home directory; or " /etc/profile " for system-wide operations. Take note that files beginning with dot ( . ) is hidden by default.
- On the Windows taskbar, right-click the Windows icon and select System.
- In the Settings window, under Related Settings, click Advanced system settings.
- On the Advanced tab, click Environment Variables.
- Click New to create a new environment variable.
More Questions
- How to buy ygg on uniswap?
- How to index in elasticsearch?
- What is after hours trading robinhood?
- What is netflix series bridgerton about?
- How to submit a bcbs claim?
- where to get brt card in lagos?
- is afoxolaner safe for dogs?
- which human centipede is the best?
- Amazon aws simple email service?
- What is mt5 trading platform?