Linux Environment Variables

Environment variables are dynamic values that affect the behavior of processes and programs in Linux. They store system information, configuration settings, and user preferences that applications can access and use.

Overview

Environment variables serve several important purposes:

  • System Configuration - Store paths, locale settings, and system preferences
  • Program Behavior - Control how applications behave and where they find resources
  • User Customization - Allow users to customize their shell and application environment
  • Security - Store sensitive information like API keys and credentials
  • Process Communication - Pass information between parent and child processes

Common Environment Variables

Variable Description Example Value
PATH Directories to search for executables /usr/bin:/bin:/usr/sbin
HOME User's home directory /home/username
USER Current username john
SHELL Default shell program /bin/bash
PWD Current working directory /home/john/documents
LANG System language and locale en_US.UTF-8
EDITOR Default text editor vim
TERM Terminal type xterm-256color

Viewing Environment Variables

Display all environment variables

env

Shows all environment variables and their values

Alternative command to view variables

printenv

Another way to display all environment variables

View specific variable

echo $PATH # or printenv PATH

Displays the value of a specific environment variable

View all variables (including shell variables)

set

Shows all variables, including shell variables and functions

Search for variables containing text

env | grep -i java

Finds all environment variables containing "java"

Setting Environment Variables

Set variable for current session

export MYVAR="Hello World"

Creates an environment variable for the current shell session

Set variable without export (shell variable only)

LOCALVAR="Local Value"

Creates a shell variable that won't be inherited by child processes

Add to PATH variable

export PATH="$PATH:/new/directory"

Appends a new directory to the existing PATH

Set variable for single command

LANG=C ls --help

Sets LANG variable only for the ls command execution

Set multiple variables

export VAR1="value1" VAR2="value2" VAR3="value3"

Sets multiple environment variables in one command

Permanent Environment Variables

User-specific variables (~/.bashrc)

# Add to ~/.bashrc export JAVA_HOME="/usr/lib/jvm/java-11-openjdk" export PATH="$PATH:$JAVA_HOME/bin" # Reload configuration source ~/.bashrc

Sets variables for the current user's bash sessions

User profile variables (~/.profile)

# Add to ~/.profile (works with all shells) export EDITOR=vim export BROWSER=firefox

Sets variables for all shell types for the current user

System-wide variables (/etc/environment)

# Add to /etc/environment (requires sudo) JAVA_HOME="/usr/lib/jvm/default-java" MAVEN_HOME="/opt/maven"

Sets variables for all users system-wide

System-wide shell variables (/etc/bash.bashrc)

# Add to /etc/bash.bashrc export HISTSIZE=10000 export HISTFILESIZE=20000

Sets bash-specific variables for all users

Note: After modifying configuration files, you need to either restart your shell or use source filename to reload the changes.

Unsetting Environment Variables

Remove environment variable

unset MYVAR

Removes the specified environment variable

Remove multiple variables

unset VAR1 VAR2 VAR3

Removes multiple environment variables at once

Temporarily unset variable for command

env -u DISPLAY firefox

Runs firefox with the DISPLAY variable temporarily removed

Special Shell Variables

Variable Description Example
$0 Script name or shell name bash
$1, $2, ... Command line arguments first_arg
$# Number of arguments 3
$@ All arguments as separate words arg1 arg2 arg3
$* All arguments as single string arg1 arg2 arg3
$$ Process ID of current shell 1234
$? Exit status of last command 0
$! Process ID of last background job 5678

Variable Expansion

Basic variable expansion

echo $HOME echo ${HOME}

Both forms access the HOME variable value

Default values

echo ${VAR:-default_value} # Use default if VAR is unset echo ${VAR:=default_value} # Set VAR to default if unset echo ${VAR:+alt_value} # Use alt_value if VAR is set echo ${VAR:?error_message} # Error if VAR is unset

Various ways to handle unset or empty variables

String manipulation

FILE="/path/to/file.txt" echo ${FILE##*/} # Extract filename: file.txt echo ${FILE%.*} # Remove extension: /path/to/file echo ${FILE/txt/log} # Replace txt with log

Extract parts of variable values or perform substitutions

Best Practices

Naming Conventions
  • Use UPPERCASE for environment variables
  • Use lowercase for local shell variables
  • Use descriptive names (JAVA_HOME vs JH)
  • Avoid spaces and special characters in names
  • Use underscores to separate words
Security Considerations
  • Don't store sensitive data in environment variables in production
  • Use proper file permissions for configuration files
  • Be careful with variables in shared environments
  • Consider using secret management tools for credentials
  • Avoid logging environment variables that contain secrets
⚠️ Security Warning: Environment variables are visible to all processes and can be seen in process lists. Never store passwords or API keys in environment variables in production systems.

Common Use Cases

Development Environment Setup

# Java development export JAVA_HOME="/usr/lib/jvm/java-11-openjdk" export PATH="$PATH:$JAVA_HOME/bin" # Node.js development export NODE_ENV="development" export PORT=3000 # Python development export PYTHONPATH="$PYTHONPATH:/path/to/modules"

Setting up development environments for different programming languages

Customizing Shell Behavior

# History settings export HISTSIZE=10000 export HISTFILESIZE=20000 export HISTCONTROL=ignoredups:erasedups # Editor and pager export EDITOR=vim export PAGER=less # Colors export CLICOLOR=1 export LSCOLORS=ExFxBxDxCxegedabagacad

Customizing shell behavior and appearance

Application Configuration

# Database connection export DB_HOST="localhost" export DB_PORT="5432" export DB_NAME="myapp" # API configuration export API_BASE_URL="https://api.example.com" export API_TIMEOUT="30"

Configuring applications through environment variables

Troubleshooting

Variable not found

# Check if variable exists if [ -z "$MYVAR" ]; then echo "MYVAR is not set" fi # List all variables containing text env | grep -i myvar

Check if variables are properly set

PATH issues

# Check current PATH echo $PATH | tr ':' '\n' # Find where command is located which command_name type command_name

Debug PATH-related issues

Configuration not loading

# Check which files are being sourced bash -x ~/.bashrc # Manually source configuration source ~/.bashrc source ~/.profile

Debug configuration file loading issues

See also