Ubuntu Environment Variables
Introduction
Environment variables are dynamic named values that can affect the way running processes behave on a computer. In Ubuntu and other Linux systems, these variables are an essential part of the shell environment and play a crucial role in system configuration and application behavior.
Environment variables serve several important purposes:
- They store system settings
- They control program behavior
- They facilitate communication between processes
- They provide a way to customize your shell experience
In this tutorial, we'll explore what environment variables are, how they work in Ubuntu, and how you can use them effectively in your shell scripts and daily operations.
Understanding Environment Variables
What Are Environment Variables?
An environment variable is simply a name-value pair stored in your system's memory. The shell and other programs can access these variables to get information about the environment in which they're running.
Think of environment variables as a way for your operating system to communicate important information to applications and scripts. For example, your system uses environment variables to tell applications:
- Where to find executable files
- What your username is
- Where your home directory is located
- What terminal type you're using
- And much more!
Key Environment Variables in Ubuntu
Let's look at some of the most common environment variables you'll encounter in Ubuntu:
Variable | Description |
---|---|
HOME | Contains the path to the current user's home directory |
USER | Contains the currently logged-in username |
PATH | Contains a colon-separated list of directories where the shell looks for commands |
PWD | Contains the present working directory |
SHELL | Contains the path to the current user's shell program |
TERM | Contains the terminal type |
LANG | Contains language and locale settings |
PS1 | Contains the primary prompt string |
Viewing Environment Variables
Displaying All Environment Variables
To display all environment variables currently set in your shell session, you can use the env
or printenv
command:
env
Sample output:
SHELL=/bin/bash
PWD=/home/user
LOGNAME=user
HOME=/home/user
LANG=en_US.UTF-8
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
...
Alternatively, you can use:
printenv
Viewing a Specific Environment Variable
To view the value of a specific environment variable, you can use the echo
command with the $
symbol before the variable name:
echo $HOME
Output:
/home/user
You can also use the printenv
command followed by the variable name:
printenv PATH
Output:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Setting Environment Variables
Temporary Variables (Session Only)
To set an environment variable for the current session only, use the export command:
export MY_VARIABLE="Hello, Ubuntu!"
You can verify it was set correctly:
echo $MY_VARIABLE
Output:
Hello, Ubuntu!
These variables will only persist for the duration of your current terminal session. Once you close the terminal, they're gone.
Persistent Environment Variables
To make environment variables persist across terminal sessions and system reboots, you need to add them to shell configuration files.
For user-specific variables, add them to your .bashrc
or .profile
file in your home directory:
echo 'export MY_VARIABLE="Hello, Ubuntu!"' >> ~/.bashrc
For system-wide variables that should apply to all users, you can add them to /etc/environment
or create a new file in the /etc/profile.d/
directory:
sudo sh -c 'echo "export GLOBAL_VAR=\"System-wide variable\"" > /etc/profile.d/my_custom_vars.sh'
After making changes to these files, you'll need to either restart your terminal or source the file to apply the changes:
source ~/.bashrc
Working with PATH Variable
The PATH
variable is particularly important as it tells the shell where to look for executable programs. It contains a colon-separated list of directories.
Viewing the PATH Variable
echo $PATH
Output:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Adding a Directory to PATH
To add a new directory to your PATH temporarily:
export PATH=$PATH:/path/to/your/directory
To add it permanently for your user, add this line to your ~/.bashrc
file:
echo 'export PATH=$PATH:/path/to/your/directory' >> ~/.bashrc
Then source the file:
source ~/.bashrc
Environment Variables in Shell Scripts
Environment variables are extremely useful in shell scripts for configuration and passing data between processes.
Using Variables in Scripts
Here's a simple script that uses environment variables:
#!/bin/bash
# Script to demonstrate environment variables
echo "Hello, $USER!"
echo "Your home directory is: $HOME"
echo "Your current shell is: $SHELL"
echo "Your current directory is: $PWD"
# Using a custom environment variable
echo "Custom variable value: $MY_VARIABLE"
Save this as env_demo.sh
, make it executable with chmod +x env_demo.sh
, and run it:
chmod +x env_demo.sh
./env_demo.sh
Sample output:
Hello, user!
Your home directory is: /home/user
Your current shell is: /bin/bash
Your current directory is: /home/user/scripts
Custom variable value: Hello, Ubuntu!
Local Variables vs. Environment Variables
In shell scripts, there's an important distinction between local variables and environment variables:
- Local variables exist only in the current shell or script
- Environment variables are inherited by child processes
To demonstrate this difference:
#!/bin/bash
# Local variable
LOCAL_VAR="I am local"
echo "Inside parent script: $LOCAL_VAR"
# Environment variable
export ENV_VAR="I am exported"
echo "Inside parent script: $ENV_VAR"
# Run a child script
bash -c 'echo "Inside child process - LOCAL_VAR: $LOCAL_VAR"; echo "Inside child process - ENV_VAR: $ENV_VAR"'
Save this as variable_scope.sh
, make it executable, and run it:
chmod +x variable_scope.sh
./variable_scope.sh
Sample output:
Inside parent script: I am local
Inside parent script: I am exported
Inside child process - LOCAL_VAR:
Inside child process - ENV_VAR: I am exported
Notice that LOCAL_VAR
isn't available in the child process, but ENV_VAR
is because it was exported.
Practical Examples
Let's look at some practical applications of environment variables in Ubuntu.
Example 1: Creating Aliases with Environment Variables
You can use environment variables to create shortcuts to commonly used directories:
export PROJECTS_DIR="$HOME/projects"
Then, in your shell scripts or commands, you can use:
cd $PROJECTS_DIR
Example 2: Configuring Application Behavior
Many applications use environment variables for configuration. For example, to configure Git with your details:
export GIT_AUTHOR_NAME="Your Name"
export GIT_AUTHOR_EMAIL="[email protected]"
Example 3: Building a Custom Prompt
You can customize your bash prompt using the PS1
environment variable:
export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(git branch 2>/dev/null | sed -n 's/* \(.*\)/(\1)/p')\[\033[00m\] $ "
This will create a custom prompt with your username, hostname, current directory, and git branch (if applicable).
Example 4: Creating a Simple Logger with Environment Variables
Here's a script that uses an environment variable to control logging verbosity:
#!/bin/bash
# log_message.sh - A simple logging script
# Default to INFO level if LOG_LEVEL is not set
LOG_LEVEL=${LOG_LEVEL:-INFO}
log_debug() {
if [[ "$LOG_LEVEL" == "DEBUG" ]]; then
echo "[DEBUG] $1"
fi
}
log_info() {
if [[ "$LOG_LEVEL" == "INFO" || "$LOG_LEVEL" == "DEBUG" ]]; then
echo "[INFO] $1"
fi
}
log_error() {
echo "[ERROR] $1"
}
# Main script logic
log_debug "This is a debug message"
log_info "This is an info message"
log_error "This is an error message"
Run with default logging level:
./log_message.sh
Output:
[INFO] This is an info message
[ERROR] This is an error message
Run with DEBUG level:
LOG_LEVEL=DEBUG ./log_message.sh
Output:
[DEBUG] This is a debug message
[INFO] This is an info message
[ERROR] This is an error message
Environment Variable Management Tips
Listing Variables by Prefix
To find all environment variables that start with a specific prefix:
env | grep "^PREFIX_"
Unsetting Variables
To remove an environment variable:
unset MY_VARIABLE
Temporary Environment Variables for a Single Command
You can set an environment variable for just a single command:
MY_VARIABLE="temporary value" my_command
Checking if a Variable Exists
In scripts, you can check if a variable exists and provide a default if it doesn't:
#!/bin/bash
# Use a default value if MY_VARIABLE isn't set
MY_SETTING=${MY_VARIABLE:-default_value}
echo "Using setting: $MY_SETTING"
Environment Variables and Security
When working with environment variables, keep these security considerations in mind:
- Never store sensitive information (like passwords or API keys) in environment variables for long-term use
- Be aware that any process you launch can access your environment variables
- Some system tools might log environment variables, potentially exposing sensitive data
- For sensitive data, consider using more secure alternatives like keyring services or encrypted configuration files
Summary
Environment variables are a powerful feature in Ubuntu and other Linux systems that allow you to:
- Configure your shell environment
- Control how applications behave
- Pass information between processes
- Create customized user experiences
Key points to remember:
- Use
export
to set variables for the current session - Edit configuration files (
~/.bashrc
,/etc/environment
) for persistent variables - The
PATH
variable determines where the shell looks for executable files - Only exported variables are passed to child processes
- Be cautious with sensitive information in environment variables
By mastering environment variables, you'll have much more control over your Ubuntu system and will be able to create more powerful and flexible shell scripts.
Exercises for Practice
- Create a script that displays all environment variables containing the word "PATH"
- Add a custom directory to your PATH and create a simple executable in it
- Create a script that behaves differently based on a DEBUG environment variable
- Set up a persistent environment variable that points to a projects folder
- Write a script that validates whether required environment variables are set
Additional Resources
- The Bash manual:
man bash
(look for the "ENVIRONMENT" section) - The Ubuntu Community Help Wiki
- Advanced Bash-Scripting Guide
- Bash Hackers Wiki
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)