Linux Variable Exporting

LinuxLinuxBeginner
Practice Now

Introduction

Environment variables play a crucial role in Linux operating systems. They are dynamic values that affect the processes running on the system. In this lab, we will explore how to use the export command in Linux to create and manage environment variables.

Environment variables are used in many scenarios such as storing configuration information, communication between processes, and defining system-wide settings. Understanding how to work with environment variables is an essential skill for any Linux user or system administrator.

This lab will guide you through the basics of setting variables, exporting them to make them available to child processes, and using them in bash scripts. You will learn how these variables can be used to create more dynamic and configurable applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("Linux")) -.-> linux/BasicFileOperationsGroup(["Basic File Operations"]) linux(("Linux")) -.-> linux/FileandDirectoryManagementGroup(["File and Directory Management"]) linux(("Linux")) -.-> linux/UserandGroupManagementGroup(["User and Group Management"]) linux(("Linux")) -.-> linux/VersionControlandTextEditorsGroup(["Version Control and Text Editors"]) linux(("Linux")) -.-> linux/BasicSystemCommandsGroup(["Basic System Commands"]) linux/BasicSystemCommandsGroup -.-> linux/echo("Text Display") linux/BasicFileOperationsGroup -.-> linux/chmod("Permission Modifying") linux/FileandDirectoryManagementGroup -.-> linux/cd("Directory Changing") linux/UserandGroupManagementGroup -.-> linux/env("Environment Managing") linux/UserandGroupManagementGroup -.-> linux/export("Variable Exporting") linux/UserandGroupManagementGroup -.-> linux/unset("Variable Unsetting") linux/VersionControlandTextEditorsGroup -.-> linux/nano("Simple Text Editing") subgraph Lab Skills linux/echo -.-> lab-271279{{"Linux Variable Exporting"}} linux/chmod -.-> lab-271279{{"Linux Variable Exporting"}} linux/cd -.-> lab-271279{{"Linux Variable Exporting"}} linux/env -.-> lab-271279{{"Linux Variable Exporting"}} linux/export -.-> lab-271279{{"Linux Variable Exporting"}} linux/unset -.-> lab-271279{{"Linux Variable Exporting"}} linux/nano -.-> lab-271279{{"Linux Variable Exporting"}} end

Understanding Basic Variables in Linux

In this step, you will learn the basics of creating and using variables in a Linux shell environment.

In Linux, variables are used to store data that can be referenced and manipulated by commands and scripts. A variable is simply a name that represents a value.

Let's start by creating a simple variable in your shell:

name="LinuxLearner"

This command creates a variable called name and assigns it the value "LinuxLearner". Note that there should be no spaces around the equals sign when assigning values to variables.

To display the value of a variable, you use the echo command with the variable name preceded by a dollar sign ($):

echo $name

You should see the output:

LinuxLearner

You can also use variables within strings:

echo "Hello, $name!"

Output:

Hello, LinuxLearner!

Now, create another variable to store your favorite color:

color="blue"

And display a message using both variables:

echo "Hello $name, I see your favorite color is $color."

Output:

Hello LinuxLearner, I see your favorite color is blue.

These variables you've created are called "shell variables" or "local variables." They are only available in the current shell session. In the next step, we'll learn how to make variables available to other processes using the export command.

Exporting Variables as Environment Variables

In the previous step, you created shell variables that are only available in your current shell session. In this step, you will learn how to use the export command to convert a shell variable into an environment variable that will be available to child processes.

Let's first understand the difference:

  • Shell Variable: Available only in the current shell
  • Environment Variable: Available to the current shell and all its child processes

To demonstrate this, let's create a new shell variable:

greeting="Welcome to Linux"

Now, let's create a new shell script that attempts to access this variable. Open a text editor and create a file called test_var.sh in the ~/project directory:

cd ~/project
nano test_var.sh

Add the following content to the file:

#!/bin/bash
echo "The greeting is: $greeting"

Save the file (press Ctrl+O, then Enter) and exit nano (press Ctrl+X).

Make the script executable:

chmod +x ~/project/test_var.sh

Now, run the script:

~/project/test_var.sh

You'll see the output:

The greeting is:

Notice that the variable value isn't displayed because shell variables are not passed to child processes.

To make this variable available to the script, you need to export it:

export greeting="Welcome to Linux"

Now run the script again:

~/project/test_var.sh

This time, you should see:

The greeting is: Welcome to Linux

Congratulations! You've successfully exported a variable, making it an environment variable that can be accessed by other processes.

You can check all current environment variables using the env command:

env

This will display a list of all environment variables in your current session.

You can also check a specific environment variable with the echo command:

echo $greeting

Now, let's create and export another environment variable:

export USER_LEVEL="beginner"

Run the following command to verify it's been set:

echo $USER_LEVEL

Output:

beginner

Creating Scripts That Use Environment Variables

In this step, you will learn how to create and run scripts that utilize environment variables for configuration. This is a common practice in software development to make applications more flexible and configurable without changing the code.

First, let's create a script that uses environment variables to customize its output. Create a new file called greet.sh in the ~/project directory:

cd ~/project
nano greet.sh

Add the following content to the file:

#!/bin/bash
## This script demonstrates using environment variables

## Default values if environment variables are not set
DEFAULT_NAME="Guest"
DEFAULT_LANGUAGE="English"

## Use environment variables or default values
USER_NAME=${USER_NAME:-$DEFAULT_NAME}
LANGUAGE=${LANGUAGE:-$DEFAULT_LANGUAGE}

## Greet based on language
if [ "$LANGUAGE" = "English" ]; then
  echo "Hello, $USER_NAME! Welcome to the Linux learning environment."
elif [ "$LANGUAGE" = "Spanish" ]; then
  echo "Hola, $USER_NAME! Bienvenido al entorno de aprendizaje de Linux."
elif [ "$LANGUAGE" = "French" ]; then
  echo "Bonjour, $USER_NAME! Bienvenue dans l'environnement d'apprentissage Linux."
else
  echo "Hello, $USER_NAME! Welcome to the Linux learning environment."
fi

Save the file (press Ctrl+O, then Enter) and exit nano (press Ctrl+X).

Make the script executable:

chmod +x ~/project/greet.sh

Now, run the script without setting any environment variables:

~/project/greet.sh

Output:

Hello, Guest! Welcome to the Linux learning environment.

The script used the default values since no environment variables were set. Let's set some environment variables and run the script again:

export USER_NAME="LinuxExplorer"
export LANGUAGE="Spanish"

Now run the script again:

~/project/greet.sh

Output:

Hola, LinuxExplorer! Bienvenido al entorno de aprendizaje de Linux.

Notice how the script output changed based on the environment variables we set. This demonstrates how environment variables can be used to configure application behavior without modifying the code.

Let's try with another language:

export LANGUAGE="French"
~/project/greet.sh

Output:

Bonjour, LinuxExplorer! Bienvenue dans l'environnement d'apprentissage Linux.

This approach is widely used in software configuration to make applications more flexible and adaptable to different environments.

Advanced Usage and Temporary Environment Variables

In this step, you will learn how to set environment variables for a single command without changing the global environment, and how to implement more advanced environment variable usage.

Setting Environment Variables for a Single Command

Sometimes you only want to set an environment variable for a single command. You can do this by prefixing the command with the environment variable assignments:

LANGUAGE="Spanish" ~/project/greet.sh

Notice that the script runs with the Spanish language setting, but the global environment variable hasn't changed:

echo $LANGUAGE

Output:

French

This is because the environment variable was only set for the duration of the command.

Environment Variables in a Real-World Scenario

Let's create a more practical example - a configuration script for a hypothetical application. Create a new file called app_config.sh:

cd ~/project
nano app_config.sh

Add the following content:

#!/bin/bash
## Application configuration script

## Display the current configuration
echo "Current Application Configuration:"
echo "--------------------------------"
echo "App Name: ${APP_NAME:-Unknown}"
echo "App Version: ${APP_VERSION:-0.0.0}"
echo "Log Level: ${LOG_LEVEL:-INFO}"
echo "Database URL: ${DB_URL:-localhost:5432}"
echo "API Key: ${API_KEY:-not set}"
echo "--------------------------------"

## Check if required configurations are set
if [[ -z "$APP_NAME" ]]; then
  echo "WARNING: APP_NAME is not set. Some features may not work properly."
fi

if [[ -z "$API_KEY" ]]; then
  echo "WARNING: API_KEY is not set. API functionality will be limited."
fi

## Validate log level
valid_log_levels=("DEBUG" "INFO" "WARNING" "ERROR" "CRITICAL")
log_level=${LOG_LEVEL:-INFO}
valid=false

for level in "${valid_log_levels[@]}"; do
  if [[ "$level" == "$log_level" ]]; then
    valid=true
    break
  fi
done

if [[ "$valid" == false ]]; then
  echo "ERROR: Invalid LOG_LEVEL '$log_level'. Must be one of: ${valid_log_levels[*]}"
  exit 1
fi

echo "Configuration validation complete."

Save the file (press Ctrl+O, then Enter) and exit nano (press Ctrl+X).

Make the script executable:

chmod +x ~/project/app_config.sh

Now, run the script without setting any environment variables:

~/project/app_config.sh

You should see warnings about missing configurations.

Now, set all required environment variables and run the script again:

export APP_NAME="MyAwesomeApp"
export APP_VERSION="1.0.0"
export LOG_LEVEL="DEBUG"
export DB_URL="postgres://user:password@dbserver:5432/mydb"
export API_KEY="abc123xyz456"

~/project/app_config.sh

You should see all the configuration values properly displayed without any warnings.

Try setting an invalid log level:

export LOG_LEVEL="VERBOSE"
~/project/app_config.sh

The script should show an error message for the invalid log level.

This example demonstrates how environment variables can be used for application configuration, with validation and default values.

Making Environment Variables Persistent

So far, we've been setting environment variables that only last for the current terminal session. Once you close your terminal or log out, these variables are lost. In this step, you'll learn how to make environment variables persistent across sessions.

Storing Environment Variables in Configuration Files

There are several files where you can set environment variables to make them persistent:

  1. ~/.bashrc or ~/.zshrc: For variables specific to a user
  2. /etc/environment: For system-wide variables
  3. /etc/profile or files in /etc/profile.d/: For system-wide variables loaded at login

Let's add some environment variables to your user's shell configuration file. Since this lab environment uses ZSH, we'll edit the ~/.zshrc file:

nano ~/.zshrc

Scroll to the bottom of the file and add the following lines:

## Custom environment variables
export EDITOR="nano"
export CUSTOM_PATH="$HOME/bin"
export GREETING="Hello from .zshrc!"

Save the file (press Ctrl+O, then Enter) and exit nano (press Ctrl+X).

To apply these changes to your current session, you need to source the file:

source ~/.zshrc

Now, check if the variables are set:

echo $EDITOR
echo $CUSTOM_PATH
echo $GREETING

You should see the values you set in the .zshrc file.

These environment variables will now be available every time you start a new shell session.

Creating a Custom Environment Variables File

A good practice for managing environment variables is to create a separate file just for them, especially for project-specific variables. This makes it easier to manage and share configurations.

Let's create a file called .env in your project directory:

cd ~/project
nano .env

Add the following content:

## Project environment variables
export PROJECT_NAME="Linux Environment Lab"
export PROJECT_VERSION="1.0.0"
export DEBUG_MODE="true"

Save the file (press Ctrl+O, then Enter) and exit nano (press Ctrl+X).

To load these variables into your current session, source the file:

source ~/project/.env

Now check if the variables are set:

echo $PROJECT_NAME
echo $PROJECT_VERSION
echo $DEBUG_MODE

You should see the values from the .env file.

Creating a Script to Load Environment Variables

Finally, let's create a script that loads environment variables from a file. This is a common pattern in development environments:

cd ~/project
nano load_env.sh

Add the following content:

#!/bin/bash
## Script to load environment variables from a .env file

ENV_FILE=".env"

if [[ -f "$ENV_FILE" ]]; then
  echo "Loading environment variables from $ENV_FILE"

  ## Read each line from the .env file
  while IFS= read -r line || [[ -n "$line" ]]; do
    ## Skip comments and empty lines
    if [[ $line =~ ^## ]] || [[ -z $line ]]; then
      continue
    fi

    ## Export the variable if it starts with "export "
    if [[ $line == export* ]]; then
      ## Remove the "export " prefix and export the variable
      eval "${line}"
      echo "Exported: ${line#export }"
    fi
  done < "$ENV_FILE"

  echo "Environment variables loaded successfully"
else
  echo "Error: $ENV_FILE file not found"
  exit 1
fi

Save the file (press Ctrl+O, then Enter) and exit nano (press Ctrl+X).

Make the script executable:

chmod +x ~/project/load_env.sh

Now, unset the variables we previously set and then run the script to load them again:

unset PROJECT_NAME PROJECT_VERSION DEBUG_MODE
echo "PROJECT_NAME: $PROJECT_NAME"

## Now load the variables using the script
~/project/load_env.sh

## Check if the variables are now set
echo "PROJECT_NAME: $PROJECT_NAME"

The script reads the .env file and exports each variable defined with the export keyword.

This approach is commonly used in development environments to manage project-specific environment variables.

Summary

In this lab, you have learned the essential concepts of working with environment variables in Linux:

  1. Basic Variables: You learned how to create and use shell variables in the current session.

  2. Environment Variables: You discovered how to use the export command to convert shell variables into environment variables that can be accessed by child processes.

  3. Using Variables in Scripts: You created scripts that read and use environment variables to customize their behavior without changing the code.

  4. Advanced Usage: You explored advanced techniques like setting variables for a single command and validating variable values in scripts.

  5. Persistent Variables: You learned how to make environment variables persistent by adding them to configuration files and creating utility scripts to load them.

Environment variables are a powerful feature in Linux that enable you to configure applications, share data between processes, and customize your environment. They are widely used in software development, system administration, and application deployment.

By mastering environment variables, you have gained an important skill that will serve you well in your Linux journey, from personal projects to enterprise-level system administration.