Set up Environment Variables in Linux with 5 Easy Examples

Posted on

Set up Environment Variables in Linux with 5 Easy Examples

Set up Environment Variables in Linux with 5 Easy Examples

In this guide, you will learn to Set up Environment Variables in Linux with Examples. Environment variables are commonly used within the bash shell. Also, it can be used for handling web app secrets and configuring services. They are also used to set the important directory location for many packages.

There are two types of shell variables:

  • Local variables: These are variables that are only available in the current shell session. They are not inherited by child processes.
  • Environment variables: These are variables that are available to the current shell session and any child processes that are spawned from it. They are used to store information that is needed by multiple programs.

Now you can follow the steps below on the Orcacore website to set environment variables for a single user and globally for all users. Also, you can list all environment variables and learn how to unset them.

To Set and Unset Environment Variables in Linux with Examples, you must have access to your server as a root or non-root user with sudo privileges.

Step 1. List All Environment Variables in Linux

At this point, you can use the set command to list all the environment variables, including shell, environment, and user-defined shell functions. To do this, you can use the command below:

set

In your output, you will see:

Set up Environment Variables in Linux

Step 2. Set an Environment Variable in Linux

Now you can use the export command to set an environment variable. The syntax for setting an environment variable is as follows:

export NAME=VALUE

You should give a name and value to your environment variable. For example:

export JAVA_HOME=/opt/openjdk11

This will set your Java environment variable, and the value of it is the path to your Java location. You can verify it by using the echo command:

echo $JAVA_HOME

This will print the directory location of your environment variable.

Step 3. Unset an Environment Variable in Linux

If you plan to remove the existence of your environment variable, you can unset it. To do this, you can use the following syntax:

unset VARIABLE_NAME

For example, you can unset the Java environment variable with the command below:

unset JAVA_HOME

Step 4. Set Persistent Environment Variables in Linux

When you set an environment variable with an export command in the shell, it will end when the user’s session ends. So to make the environment variable persistent for the user’s environment, you can use the user’s bash profile.

To do this, open the user bash profile file with your desired text editor like vi editor or nano editor:

vi ~/.bash_profile

For example, we add the export command with our Java environment variable in the file:

export JAVA_HOME=/opt/openjdk11

When you are done, save and close the file.

Then, source the bash profile file with the command below:

source ~/.bash_profile

This will make the environment variable persistent.

Step 5. Set Environment Variables Globally for All Users in Linux

At this point, you can set the environment variables globally that can be loaded for all the users in the system. All the global settings are stored in the /etc/profile directory. You must create the environment variables under this directory that can be loaded for all users.

For example, we create and open an HTTP_PROXY file for our environment variable:

vi /etc/profile.d/http_proxy.sh

Add the desired environment variables to it:

export HTTP_PROXY=http://my.proxy:8080
export HTTPS_PROXY=https://my.proxy:8080
export NO_PROXY=localhost,::1,.example.com

When you are done, save and close the file. This HTTP_PROXY environment variable can now be loaded for all users globally.

With this option, you can make your environment variables global.

Alternative Solutions for Setting Environment Variables in Linux

While the previous methods are effective, there are alternative approaches to managing environment variables in Linux. These methods offer different levels of scope and persistence.

1. Using dotenv Files:

A popular method for managing environment variables, especially in application development, is using .env files. This approach involves storing key-value pairs in a plain text file named .env located in the project’s root directory. A utility like dotenv is then used to load these variables into the environment when the application starts.

  • Explanation: This method keeps configuration separate from the application code, making it easier to manage different environments (development, testing, production). It also avoids hardcoding sensitive information directly into the source code.

  • Implementation:

    1. Install dotenv: The specific installation method depends on your programming language. For Python, you would use pip install python-dotenv. For Node.js, you’d use npm install dotenv.

    2. Create a .env file: In your project’s root directory, create a file named .env and add your environment variables:

    DATABASE_URL=postgresql://user:password@host:port/database
    API_KEY=YOUR_API_KEY
    DEBUG=True
    1. Load the variables in your code:

    Python Example:

    import os
    from dotenv import load_dotenv
    
    load_dotenv()  # Load environment variables from .env
    
    database_url = os.getenv("DATABASE_URL")
    api_key = os.getenv("API_KEY")
    debug_mode = os.getenv("DEBUG") == "True"
    
    print(f"Database URL: {database_url}")
    print(f"API Key: {api_key}")
    print(f"Debug Mode: {debug_mode}")

    Node.js Example:

    require('dotenv').config(); // Load environment variables from .env
    
    const databaseUrl = process.env.DATABASE_URL;
    const apiKey = process.env.API_KEY;
    const debugMode = process.env.DEBUG === 'true';
    
    console.log(`Database URL: ${databaseUrl}`);
    console.log(`API Key: ${apiKey}`);
    console.log(`Debug Mode: ${debugMode}`);
  • Advantages:

    • Simple to use.
    • Keeps configuration separate from code.
    • Avoids hardcoding sensitive information.
    • Works well with version control systems (ensure the .env file is added to .gitignore).
  • Disadvantages:

    • Requires a separate dotenv library.
    • Variables are only available within the application that loads them. Not system-wide.

2. Using systemd Environment Variables (for Services):

When managing services using systemd, a more robust and recommended method is to define environment variables directly within the service unit file.

  • Explanation: systemd is the system and service manager for Linux. By defining environment variables within the service unit file, you ensure that the service has the correct configuration when it starts, and it provides a cleaner separation of concerns than setting global environment variables.

  • Implementation:

    1. Locate the service unit file: Service unit files are typically located in /etc/systemd/system/ or /usr/lib/systemd/system/. For example, if your service is named myapp.service, the unit file might be /etc/systemd/system/myapp.service.

    2. Edit the service unit file: Open the service unit file with a text editor and add the Environment= directive within the [Service] section:

    [Unit]
    Description=My Application Service
    
    [Service]
    ExecStart=/path/to/my/application
    Environment=DATABASE_URL=postgresql://user:password@host:port/database
    Environment=API_KEY=YOUR_API_KEY
    Environment=DEBUG=True
    Restart=on-failure
    
    [Install]
    WantedBy=multi-user.target
    1. Reload systemd and restart the service:
    sudo systemctl daemon-reload
    sudo systemctl restart myapp.service
  • Advantages:

    • Specific to the service, avoiding potential conflicts with other applications.
    • Clean separation of concerns.
    • Managed directly by systemd, ensuring the service starts with the correct environment.
  • Disadvantages:

    • Only applicable to services managed by systemd.
    • Requires editing service unit files.

Conclusion

This guide has covered how to Set up Environment Variables in Linux with Examples, including setting them temporarily, persistently for a single user, and globally for all users. Understanding environment variables is crucial for managing configurations, secrets, and dependencies in your Linux system. We also explored two alternative methods using .env files and systemd environment variables. Remember to choose the method that best suits your needs based on scope, persistence, and security considerations. Managing environment variables properly will help you create more manageable, secure, and portable applications and systems. Using these examples helps to Set up Environment Variables in Linux with Examples in an efficient manner. These examples help Set up Environment Variables in Linux with Examples in an efficient manner.

Leave a Reply

Your email address will not be published. Required fields are marked *