Exporting Environment Variables In Linux

Dealing with Environment Variable in Linux

Exporting Environment Variables In Linux

Open your Linux terminal and run the env command.

The output of the env command displays a list of all the current environment variables and their values. If you do not understand the output on your screen, don't worry this article is here to guide you. This brings us to the definition of some terms.

A computing environment is a platform that facilitates the execution of programs and computational tasks. Comprising hardware and software components, including a processor and an operating system.

In computer science, a variable is a location where a value can be stored, such as text, number, or other data. It is typically identified by a symbolic name that is assigned during its creation, and the stored value can be viewed, removed, modified, and saved. Variables play an important role in computer programming because they enable programmers to write flexible programs. As they are related to the operating systems that we work on, it is important to know some of them and how we can influence them.

Environment variables are dynamic values that can impact the processes or programs on a computer. These variables exist in every operating system. They can be created, edited, saved, or deleted. They provide information about the system's behaviour while altering how software or programs behave.

In Linux, Environment variables are a fundamental concept, and they are used to store information that can be accessed by programs, scripts, users, and other system processes. When a program needs to access data stored in an environment variable, it simply references the variable by name, and the value stored in the variable will be used. Environment variables are there to store configuration values that are specific to different stages of your application (e.g. development and production). This way you can easily configure different settings for different environments without hard coding them.

Objectives

  • Definition and purpose of environment variables in Linux.

  • How to set environment variables temporarily and permanently.

  • How to export environment variables for use in scripts or applications.

  • Practical examples to illustrate the above concepts.

Prerequisite

  • Linux operating system

  • Comfortability using Linux terminal and terminal-based text editor.

Setting and Exporting Environment Variables

In Linux, environment variables are created and managed by the shell, which is the program that interprets and executes commands typed at the command prompt. When a new shell session is started, a set of default environment variables are created and initialized with default values. These variables are inherited by any program or script that runs from that shell session. A shell session can be referred to as a process. Processes run in the memory, and if a process is terminated or dies, all the data, along with that process will also be lost.

So let's see how we can store variables and retrieve them from the bash shell, or bash process.

There are several ways to set environment variables in Linux, each with its advantages and drawbacks. We'll be seeing at least four different ways in this article;

  • Setting variables in the current shell session

  • Setting variables in the user's profile

  • Setting variables system-wide

  • Using an external configuration file

Setting variables in the current shell session

If you're probably testing out things, you're better off setting variables in the current shell session.

Use the export command followed by the variable name and value separated by an equal sign to set variables in the current shell session.

For example, to set the variable BROWSER to the value firefox, run the following command;

$ export BROWSER=firefox

That's how to store a variable in the current shell session. To retrieve the variable, we have to use the dollar sign and the variable name.

Now, if we are trying to print the variable, we know the command to print is echo. So we can run echo $BROWSER which will access the value of the variable and display it on the screen. Here the dollar sign is important, if not given, the BROWSER is just another text.

Drawbacks of setting variables in the current shell session

  • Storing sensitive data (like passwords or API keys) as environment variables in the current shell session creates security risks as they can be accessed by other users or processes.

  • If you have many variables that you need to set, it can become difficult to manage them all in the current shell session. It's often better to store variables in configuration files that can be sourced by the shell when needed.

  • Setting variables in the current shell session limits their availability to only that session and its child processes. Once the session or shell is terminated, the variables are lost.

  • Setting a variable with the same name as an existing system variable can cause conflicts and unexpected behavior, especially if it overwrites a system variable used by other applications or scripts.

Setting variables in the user's profile

What if we want to make variables permanent for a user at any time in the system? We can achieve this by editing the user config files which get loaded each time the user logs in. Linux is a multi-user OS where multiple users can use the system at the same time, each with their account, username, password, and home directory for storing their files and configurations.

In Linux, setting variables in a user's profile involves adding the necessary commands to one of the user's configuration files, such as .bashrc, .bash_profile, or .profile. These files are located in a user's home directory and are executed each time the user logs in to the system. Run ls -a to list all files in a user's home directory.

To set variables in a user's profile, open the desired configuration file in a text editor(vim or nano), then append a line to the end of the file that sets the variables using the export command.

For example, to set the variable DISTRO to the value debian using the .bashrc file and vim as the text editor.

  • In the user home directory, run vim .bashrc to open the file.

  • Once the file is open and content displayed. Press i on your keyboard to activate the insert mode.

  • Add the following line to the end of the file;

# ~/.bashrc: executed by bash(1) for non-login shells.
....
....
export DISTRO=debian
~
~
  • Press the Esc key, then type :wq and press the Enter key to save the file.

If you're not familiar with using vim or nano text editor. You can make use of output redirection to update the configuration file.

$ echo "export DISTRO=debian" >> .bashrc

The above command simply redirects the output of the echo command into the .bashrc file, appending it to the already existing file content.

To load the variable, log out and log in again or close the current shell session and open a new one. If you do not want to log out or close the current shell session due to one reason or another before being able to load and access the variable. Simply Run source .bashrc command. This will execute(source) the .bashrc file and export the variables.

After adding this line and saving the file, the DISTRO variable will be set each time the user logs in to the system, and it will be available to any shell session opened by the user. This method provides a way to set persistent variables that are available across multiple sessions and even after a system reboot.

Drawbacks of setting variables in the user's profile

  • If sensitive information is stored in environment variables, it can be accessed by anyone who has access to the user's profile.

  • Environment variables set in a user's profile can be hard to update or remove, causing outdated or irrelevant information to remain stored.

  • If too many environment variables are set in a user's profile, it can impact the performance of the system. This can slow down response times or even cause crashes in extreme cases.

  • Environment variables set in a user's profile may not be compatible with other processes or applications. This can result in errors or issues when trying to integrate or use the information from the profile in other contexts.

Setting variables system-wide

While it is possible to set environment variables on a per-user basis, there are times when it is necessary to set environment variables system-wide, so that all users and processes have access to them.

To set variables system-wide in Linux, modify the system's environment file. The location and name of this file may defer depending on the Linux distribution, but it's typically located at /etc/environment or /etc/profile.

Importantly, modifying a system-wide config file requires having root privileges and permission

For example, let's set the variable JAVA_HOME to the value /usr/lib/jvm/java-11-openjdk-amd64. This variable holds a value specifying the path to the JDK installation directory in the system, allowing users to easily reference it.

  • Run the command below to become the root user;

      $ sudo -i
    
  • Open the config file in a text editor (vim);

      $ vim /etc/profile
    
  • Once the file is open and content displayed. Press i on your keyboard to activate the insert mode and add the following line to the end of the file;

      # /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
      # and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).
      .....
      .....
      .....
      export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
      ~
      ~
    
  • Press the Esc key, then type :wq and press the Enter key to save.

As shown earlier, you can also make use of output redirection to update the configuration file.

# run command as root user
sudo echo "JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64" >> /etc/profile

For the variable to be loaded and available to other users they'll be required to log out and log in again.

As a root user If you do not want to log out or close the current shell session due to one reason or another before being able to access the variable. Simply Run source /etc/profile command. This will execute(source) the /etc/profile file and export the variables.

After adding this line and saving the file, the JAVA_HOME variable is made available to all users and processes on the system at all times, allowing them to easily reference it.

Note, the .bashrc config file has higher precedence than the /etc/profile config file. Hence, if you want to make variables permanent for everyone, then edit the/etc/profile file. If you want to make variables permanent for a specific user, then edit the .bashrc file of that user.

Drawbacks of setting variables system-wide

  • Setting variables system-wide can limit the flexibility of individual applications or users to customize their configurations. It can also make it difficult to test and deploy new configurations in isolation, without affecting other parts of the system.

  • When variables are set system-wide, it can be difficult to track down and debug issues related to those variables. It can also be challenging to maintain and update them over time, especially if different applications or services depend on different versions or configurations of the variables.

  • Setting variables system-wide may introduce security risks, especially if the variables contain sensitive information like passwords or API keys. If these variables are accessible to unauthorized users, they can be exploited for malicious purposes.

Using an external configuration file

Using an external configuration file to export environment variables is a common practice that provides several benefits over setting variables in users' profiles or system-wide. It allows for greater flexibility, maintainability, and security when managing environment variables.

The main steps involved in creating and making use of external config files are;

  1. Choose the file location: Choose a suitable location to store your configuration file. A common location is /etc/profile.d/ or /etc/environment.d/, which is a directory where you can store shell scripts that will be run during login.

  2. Create the configuration file: Create a new file with the extension .sh or .conf in the location.

  3. Add variables: In the file created, add each environment variable you want to set, one per line, in the format export VARIABLE_NAME=value.

  4. Save the file: Save the file once you have added all the variables of interest.

  5. Set the file permissions: Make sure the file permissions are set so that only the users who need to access the environment variables can read the file.

  6. Load the variables: For other users to load the variables into their profile there'll be required to log out and log back in. As a root user use the source command to load them without logging out.

  7. Verify the variables: To verify that the variables have been loaded correctly, you can use the env command to list all environment variables or echo and grep to search for a specific variable.

Note, modifying files in /etc/ directory requires having root privileges and permissions.

For example, let's take an instance where there's a need to set variables for a database service so that other users and processes can reference them.

  • Using /etc/profile.d/ as the chosen location.

  • Switch to the root user

      $ sudo -i
    
  • Create a new file named db_data.sh

      $ touch /etc/profile.d/db_data.sh
    
  • Using vim as the text editor, execute vim /etc/profile.d/db_data.sh to open the file.

      $ vim /etc/profile.d/db_data.sh
    
  • Press i on your keyboard to activate insert mode, and add the following lines to the file

      export DATABASE_URL=mysql://user:password@localhost/myapp
      export SECRET_KEY=mysecretkey
      export DATABASE_NAME=mydatabase
      export DEBUG=true
    
  • Press Esc key, then type :wq and press the Enter key to save the file.

  • Set the file permissions by executing chmod 644 /etc/profile.d/db_data.sh.

  • To load the variables log out and log back in, or you can use the source command to load them without having to log out.

      source /etc/profile.d/db_data.sh
    
  • Verify the variables are loaded

Using output redirection;

# execute as root user
$ sudo echo -e "export DATABASE_URL=mysql://user:password@localhost/myapp \nexport SECRET_KEY=mysecretkey \nexport DATABASE_NAME=mydatabase \nexport DEBUG=true" >> /etc/profile.d/db_data.sh && chmod 644 /etc/profile.d/db_data.sh

By using an external configuration file to set environment variables, it's easy to manage and modify the variables without affecting the rest of your system. It provides an added layer of security by limiting access to the variables only to those who have permission to access the file.

Drawbacks of using an external configuration

  • Using an external configuration file to set environment variables can potentially slow down the startup time of the application, as the application needs to read the configuration file and set the environment variables before it can start. This can be especially problematic for applications that require quick startup times.

  • When environment variables are set within a configuration file, it can be difficult to manage changes to the configuration file through version control. This can make it challenging to track changes and identify the source of any problems.

Note, when you modify a config file to export variables as a root user, It is most likely that for other users to access the variables there'll be required to log out and log in again. But as a root user, you can run the source command to export the variable in your current shell.

Conclusion

In conclusion, exporting environment variables is an essential task for configuring and customizing Linux systems to meet your specific needs. By understanding the basics of environment variables, including how to view, set, and export them, you can gain greater control over your system and optimize its performance.

Whether you are working on a personal project or managing a complex enterprise environment, exporting environment variables is a fundamental tool that can help you get the most out of your Linux system.

By following best practices, such as properly naming variables, using quotes, and prioritizing variable sources, you can ensure that your exported environment variables are reliable, secure, and flexible. With these tips in mind, you'll be well on your way to becoming an expert in exporting environment variables in Linux.