Environment Variables in Linux

LinuxLinuxBeginner
Practice Now

Introduction

Welcome to this hands-on lab about environment variables in Linux! Environment variables are dynamic values that can affect the behavior of running processes on a computer. They play a crucial role in system configuration and program execution. By mastering environment variables, you'll gain essential skills for Linux system administration and software development.

In this lab, you'll learn how to create, view, modify, and delete environment variables. We'll also explore how to make these changes permanent and understand some of the most important built-in environment variables in Linux. Whether you're a beginner or looking to solidify your understanding, this lab will provide valuable hands-on experience.

Let's get started!


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/InputandOutputRedirectionGroup(["`Input and Output Redirection`"]) linux(("`Linux`")) -.-> linux/TextProcessingGroup(["`Text Processing`"]) linux(("`Linux`")) -.-> linux/UserandGroupManagementGroup(["`User and Group Management`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) linux/BasicSystemCommandsGroup -.-> linux/source("`Script Executing`") linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") linux/InputandOutputRedirectionGroup -.-> linux/pipeline("`Data Piping`") linux/InputandOutputRedirectionGroup -.-> linux/redirect("`I/O Redirecting`") linux/TextProcessingGroup -.-> linux/sort("`Text Sorting`") linux/UserandGroupManagementGroup -.-> linux/env("`Environment Managing`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") linux/FileandDirectoryManagementGroup -.-> linux/mkdir("`Directory Creating`") linux/BasicFileOperationsGroup -.-> linux/ls("`Content Listing`") linux/BasicFileOperationsGroup -.-> linux/mv("`File Moving/Renaming`") linux/BasicFileOperationsGroup -.-> linux/chmod("`Permission Modifying`") linux/UserandGroupManagementGroup -.-> linux/set("`Shell Setting`") linux/UserandGroupManagementGroup -.-> linux/export("`Variable Exporting`") linux/UserandGroupManagementGroup -.-> linux/unset("`Variable Unsetting`") subgraph Lab Skills linux/source -.-> lab-385274{{"`Environment Variables in Linux`"}} linux/echo -.-> lab-385274{{"`Environment Variables in Linux`"}} linux/pipeline -.-> lab-385274{{"`Environment Variables in Linux`"}} linux/redirect -.-> lab-385274{{"`Environment Variables in Linux`"}} linux/sort -.-> lab-385274{{"`Environment Variables in Linux`"}} linux/env -.-> lab-385274{{"`Environment Variables in Linux`"}} linux/cd -.-> lab-385274{{"`Environment Variables in Linux`"}} linux/mkdir -.-> lab-385274{{"`Environment Variables in Linux`"}} linux/ls -.-> lab-385274{{"`Environment Variables in Linux`"}} linux/mv -.-> lab-385274{{"`Environment Variables in Linux`"}} linux/chmod -.-> lab-385274{{"`Environment Variables in Linux`"}} linux/set -.-> lab-385274{{"`Environment Variables in Linux`"}} linux/export -.-> lab-385274{{"`Environment Variables in Linux`"}} linux/unset -.-> lab-385274{{"`Environment Variables in Linux`"}} end

Understanding Variables in Linux

Before we dive into environment variables, let's start with basic shell variables. This will help you understand the concept of variables in Linux.

  1. Open your terminal. You should be in the /home/labex/project directory. If not, you can change to this directory using the following command:

    cd /home/labex/project
  2. Now, let's create a simple shell variable. In Linux, you can create a variable by simply assigning a value to a name. Let's create a variable named my_var:

    my_var="Hello, Linux"

    Note: There should be no spaces around the equals sign (=) when assigning variables in bash.

  3. To view the value of the variable, we use the echo command with a $ before the variable name. The $ tells the shell to substitute the value of the variable:

    echo $my_var

    You should see the output:

    Hello, Linux
  4. You can also use variables within other commands or assignments. For example:

    echo "The value of my_var is: $my_var"

    This will output: The value of my_var is: Hello, Linux

Great job! You've just created and used your first shell variable. However, this variable is only available in the current shell session. If you open a new terminal window or tab, this variable won't be available there. This is where environment variables come in handy.

Introduction to Environment Variables

Now that we understand basic variables, let's explore environment variables. Environment variables are variables that are available to any child process of the shell. This means they can be accessed by scripts and programs run from that shell.

  1. To view all current environment variables, use the env command:

    env

    This will display a long list of variables. Don't worry if you don't understand all of them yet - we'll cover some of the most important ones later.

  2. One of the most important environment variables is PATH. Let's take a look at it:

    echo $PATH

    The PATH variable lists directories where the system looks for executable programs. Each directory is separated by a colon (:).

  3. Now, let's create our own environment variable. We use the export command to create an environment variable:

    export MY_ENV_VAR="This is an environment variable"

    The export command makes the variable available to child processes. This is the key difference between shell variables and environment variables.

  4. To illustrate the difference, let's create a shell script that tries to access both a regular shell variable and an environment variable:

    echo '#!/bin/bash
    echo "Shell variable: $my_var"
    echo "Environment variable: $MY_ENV_VAR"' > test_vars.sh

    Make the script executable:

    chmod +x test_vars.sh

    Now run the script:

    ./test_vars.sh

    You should see that the environment variable (MY_ENV_VAR) is accessible, while the shell variable (my_var) is not.

  5. To verify that MY_ENV_VAR is now an environment variable, we can use the env command again, but this time we'll filter the output using grep:

    env | grep MY_ENV_VAR

    You should see your new variable in the output.

  6. You can also check the value of your new environment variable directly:

    echo $MY_ENV_VAR

Excellent! You've now created your first environment variable and seen how it differs from a shell variable. The key difference is that environment variables, created with export, are available to child processes, while shell variables are not.

Modifying the PATH Environment Variable

The PATH variable is one of the most important environment variables in Linux. It tells the system where to look for executable files. Let's modify it to include a new directory.

  1. First, let's create a new directory where we might store custom scripts:

    mkdir ~/my_scripts

    This creates a directory called my_scripts in your home directory.

  2. Now, let's add this new directory to your PATH. We'll use the export command, but this time we're modifying an existing variable:

    export PATH="$PATH:$HOME/my_scripts"

    Let's break this down:

    • $PATH is the current value of PATH
    • : is used to separate directories in the PATH
    • $HOME is an environment variable that points to your home directory
    • So we're appending :$HOME/my_scripts to the existing PATH
  3. Verify that the new directory has been added:

    echo $PATH

    You should see /home/labex/my_scripts at the end of the PATH.

  4. To test this, let's create a simple script in our new directory:

    echo '#!/bin/bash
    echo "Hello from my custom script!"' > ~/my_scripts/hello.sh
  5. Make the script executable:

    chmod +x ~/my_scripts/hello.sh
  6. Now, you should be able to run this script from anywhere by just typing its name:

    hello.sh

    If everything worked correctly, you should see: Hello from my custom script!

This works because we added the my_scripts directory to the PATH. When you type a command, the shell looks for an executable file with that name in each of the directories listed in the PATH, in order. By adding my_scripts to the PATH, we've told the shell to look there for executables as well.

To demonstrate this, try changing to a different directory and running the script again:

cd /tmp
hello.sh

You'll see that the script still runs, even though you're not in the directory where it's located. This is the power of the PATH variable - it allows you to run executables from anywhere in the system, as long as they're in a directory listed in the PATH.

Great job! You've successfully modified the PATH environment variable and created a custom script that can be run from anywhere.

Making Environment Variables Permanent

The environment variables we've set will be lost when you close the terminal. To make them permanent, we need to add them to a shell configuration file. The exact file depends on which shell you're using.

In this lab environment, we're using the Z shell (zsh), which is an extended version of the Bourne Shell (sh), with many improvements, including some features of Bash, ksh, and tcsh. Zsh has become increasingly popular and is now the default shell in macOS.

If you were using Bash (which is still the default on many Linux distributions), you would modify .bashrc. However, since we're using Zsh, we'll modify .zshrc.

  1. Open the .zshrc file in your home directory with a text editor. We'll use nano, which is a simple terminal-based text editor:

    nano ~/.zshrc
  2. Scroll to the bottom of the file (you can use the arrow keys), and add the following lines:

    export MY_ENV_VAR="This is an environment variable"
    export PATH="$PATH:$HOME/my_scripts"
  3. Save the file and exit the editor. In nano, you do this by pressing Ctrl+X, then Y, then Enter.

  4. To apply these changes without restarting your terminal, use the source command:

    source ~/.zshrc

    The source command reads and executes commands from the file specified as its argument in the current shell environment.

Now, these environment variables will be set every time you open a new terminal. This is incredibly useful for setting up your development environment consistently.

Understanding Important Environment Variables

Linux has several built-in environment variables that are crucial for system operation. Let's explore some of them:

  1. HOME: Points to the home directory of the current user.

    echo $HOME
  2. USER: Contains the username of the current user.

    echo $USER
  3. SHELL: Specifies the user's default shell.

    echo $SHELL
  4. PWD: Stands for "Print Working Directory". It contains the path of the current directory.

    echo $PWD
  5. TERM: Specifies the type of terminal to emulate when running the shell.

    echo $TERM

Understanding these variables can help you better navigate and control your Linux environment.

Unsetting Environment Variables

Sometimes, you may need to remove an environment variable. This is done using the unset command.

  1. First, let's check if our MY_ENV_VAR is still set:

    echo $MY_ENV_VAR

    You should see the value we set earlier.

  2. To unset (remove) this variable, use the unset command:

    unset MY_ENV_VAR
  3. Verify that the variable has been unset:

    echo $MY_ENV_VAR

    You should see no output, indicating that the variable no longer exists.

  4. You can also use the -v option with unset to ensure you're unsetting a variable and not a shell function:

    unset -v MY_ENV_VAR

Remember, if you've added the variable to your .zshrc file, it will be recreated the next time you open a terminal or source the .zshrc file.

Summary

Congratulations! You've completed this comprehensive lab on Linux environment variables. Let's recap what you've learned:

  1. You created and accessed simple shell variables.
  2. You learned about environment variables and how they differ from shell variables, particularly in their accessibility to child processes.
  3. You modified the important PATH variable to include a custom directory, allowing you to run scripts from anywhere in the system.
  4. You made environment variables permanent by adding them to .zshrc, understanding the difference between Bash and Zsh shell configurations.
  5. You explored some of the most important built-in environment variables in Linux.
  6. Finally, you learned how to unset (remove) environment variables.

These skills are fundamental for Linux system administration and software development. Environment variables allow you to configure your system and applications flexibly. As you continue working with Linux, you'll find countless uses for environment variables in scripting, development, and system configuration.

Remember, practice makes perfect. Try creating your own environment variables for different purposes, and explore how various applications and scripts use environment variables to control their behavior. Happy learning!

Other Linux Tutorials you may like