Linux Environment Variables: PATH, HOME, USER, and Shell Configuration
Master Linux environment variables including PATH, HOME, USER, SHELL, setting variables, .bashrc, .profile, and environment variable best practices.
Linux Environment Variables: PATH, HOME, USER, and Shell Configuration
Environment variables are values that your shell and programs can access to modify behavior. They're essential for system configuration, user preferences, and application settings.
Viewing Environment Variables
env - Display All Variables
# View all environment variables
env
# PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
# HOME=/home/john
# USER=john
# SHELL=/bin/bash
# PWD=/home/john
# ... and many more
# View specific variable
env | grep PATH
# PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
# Count environment variables
env | wc -l
# 35printenv - Print Environment
# Print all variables
printenv
# Print specific variable
printenv PATH
# /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
# Print variables matching pattern
printenv | grep LANG
# LANG=en_US.UTF-8
# Check if variable exists
if printenv HOME > /dev/null; then
echo "HOME is set to: $(printenv HOME)"
fiecho - Access Variable
# Access variable with $
echo $PATH
# /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
echo $HOME
# /home/john
echo $USER
# john
echo $SHELL
# /bin/bash
# Access variable with ${...}
echo ${HOME}
# /home/john
# Safer syntax for complex cases
echo "${HOME}/documents"
# /home/john/documents
# Default values
echo ${UNDEFINED_VAR:-default_value}
# default_value (if UNDEFINED_VAR is not set)Common Environment Variables
PATH - Executable Search Path
Colon-separated list of directories where the shell looks for executables.
# View PATH
echo $PATH
# /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
# Add directory to PATH (for current session)
export PATH=$PATH:/usr/local/go/bin
echo $PATH
# /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin
# Add to beginning of PATH (higher priority)
export PATH=/usr/local/bin:$PATH
# Find which command is executed
which python3
# /usr/bin/python3
# Show all matches in PATH
which -a python3
# /usr/bin/python3
# /usr/local/bin/python3
# Check if directory is in PATH
if [[ ":$PATH:" == *":/usr/local/bin:"* ]]; then
echo "Directory is in PATH"
fiHOME - User Home Directory
# View HOME
echo $HOME
# /home/john
# Use HOME in paths
cd $HOME/documents
cd ~/documents # ~ is shorthand for $HOME
# HOME for different users
echo $HOME
# /home/john
sudo -u sarah bash -c 'echo $HOME'
# /home/sarah
# Root's home
sudo bash -c 'echo $HOME'
# /rootUSER and LOGNAME - Current User
# Current user
echo $USER
# john
# Logged-in user
echo $LOGNAME
# john
# Both show same value for regular login
# Different for su (substitute user) command
su - sarah
echo $USER # sarah
echo $LOGNAME # john (original user)
exitSHELL - Default Shell
# Default shell
echo $SHELL
# /bin/bash
# Run shell
$SHELL
# New shell session starts
# Change default shell
chsh -s /bin/zsh
echo $SHELL
# /bin/zsh (after restart)
# Other common shells
chsh -s /bin/sh # POSIX shell
chsh -s /bin/dash # Lightweight shell
chsh -s /bin/ksh # Korn shellPWD and OLDPWD - Current Directory
# Print working directory
echo $PWD
# /home/john
# Change directory and track previous
cd /etc
echo $PWD
# /etc
# Go back to previous directory
cd $OLDPWD
echo $PWD
# /home/john
# Shorthand for previous directory
cd -
echo $PWD
# /etcAdditional Important Variables
# Language and locale settings
echo $LANG
# en_US.UTF-8
echo $LC_ALL
# (usually empty)
# Term type
echo $TERM
# xterm-256color
# Editor
echo $EDITOR
# nano
# Pager
echo $PAGER
# less
# Mail
echo $MAIL
# /var/mail/john
# Temporary directory
echo $TMPDIR
# (usually empty, defaults to /tmp)
# History file
echo $HISTFILE
# /home/john/.bash_history
# History size
echo $HISTSIZE
# 1000Setting Variables
Temporary Variables (Current Session)
# Create variable
MYVAR="Hello World"
echo $MYVAR
# Hello World
# Use in command
echo "The value is: $MYVAR"
# The value is: Hello World
# Variable with spaces (quote it)
NAME="John Doe"
echo $NAME
# John Doe
# Variable without quotes (splits on spaces)
VALUE=123 456
# Error: 456 command not found
# Variable with value
RESULT=$(echo "hello" | tr 'a-z' 'A-Z')
echo $RESULT
# HELLO
# Append to variable
VAR1="Hello"
VAR2="$VAR1 World"
echo $VAR2
# Hello World
# Variable only exists in current shell
bash # New shell
echo $MYVAR
# (empty)
exitExport - Make Variable Global
# Export variable (available to subshells/child processes)
export MYVAR="Global Value"
echo $MYVAR
# Global Value
# Child process can access exported variable
bash -c 'echo $MYVAR'
# Global Value
# Non-exported variable is not available to child
LOCALVAR="Local"
bash -c 'echo $LOCALVAR'
# (empty)
# Export existing variable
VAR="Value"
export VAR
# Export and assign together
export API_KEY="12345"
# View exported variables
export -p
# declare -x API_KEY="12345"
# declare -x HOME="/home/john"Shell Configuration Files
Execution Order
1. /etc/profile (system-wide login shell)
2. ~/.profile (user login shell)
3. ~/.bash_profile (bash login shell)
4. ~/.bashrc (bash interactive shell)
5. ~/.bash_logout (bash logout)
~/.bashrc - Interactive Shell Configuration
# Edit bashrc
nano ~/.bashrc
# Common settings in .bashrc:
# Aliases
alias ll='ls -la'
alias c='clear'
alias grep='grep --color=auto'
# PATH additions
export PATH=$PATH:$HOME/.local/bin
export PATH=$PATH:/opt/custom/bin
# Environment variables
export EDITOR=nano
export HISTSIZE=10000
# Functions
function greet() {
echo "Hello, $1!"
}
# Prompt customization
export PS1="\u@\h:\w$ " # user@host:directory$
# Source other files
if [ -f ~/.bashrc_custom ]; then
source ~/.bashrc_custom
fi~/.profile - Login Shell Configuration
# Edit profile
nano ~/.profile
# Usually sources .bashrc
if [ -f "$HOME/.bashrc" ]; then
source "$HOME/.bashrc"
fi
# Add to PATH for login shells
export PATH=$HOME/.local/bin:$PATH
# Set environment variables
export EDITOR=vim
export VISUAL=vim
# Application-specific settings
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk
export ANDROID_SDK_ROOT=$HOME/Android/Sdk
# Verify changes
source ~/.profile
echo $EDITOR
# vim~/.bash_logout - Logout Configuration
# Commands run when logging out
# Clear screen
clear
# Clear history
history -c
# Custom message
echo "Goodbye!"Persistent Environment Configuration
Per-User Configuration
# Edit .bashrc
echo 'export CUSTOM_VAR="my_value"' >> ~/.bashrc
source ~/.bashrc
# Edit .profile
echo 'export JAVA_HOME=/usr/lib/jvm/java-11' >> ~/.profile
source ~/.profile
# Create custom configuration file
cat > ~/.bashrc_custom << 'EOF'
# Custom aliases
alias dev='cd ~/projects/development'
alias deploy='./scripts/deploy.sh'
# Custom functions
function mkcd() {
mkdir -p "$1" && cd "$1"
}
# Custom exports
export WORKSPACE=$HOME/projects
EOF
# Source in .bashrc
echo 'source ~/.bashrc_custom' >> ~/.bashrcSystem-Wide Configuration
# Edit system profile (root)
sudo nano /etc/profile
# All users' profile startup
sudo nano /etc/bash.bashrc
# Example: Add to system PATH
echo 'export PATH=$PATH:/opt/custom/bin' | sudo tee -a /etc/profile
# Apply to all users
sudo source /etc/profileWorking with Variables in Scripts
Variable Types
#!/bin/bash
# String variable
NAME="John"
echo $NAME
# Number variable
AGE=30
echo $AGE
# Array variable
FRUITS=("apple" "banana" "orange")
echo ${FRUITS[0]} # apple
echo ${FRUITS[@]} # all elements
# Associative array
declare -A COLORS
COLORS[red]="#FF0000"
COLORS[green]="#00FF00"
echo ${COLORS[red]} # #FF0000
# Read-only variable
readonly VERSION="1.0"
VERSION="2.0" # Error: cannot assignVariable Expansion
# Basic expansion
echo "Hello $NAME"
# Expansion with braces
echo "${NAME}_suffix"
# Provide default value
echo ${UNDEFINED:-"default"}
# Use default if empty
echo ${EMPTYVAR:="default_value"}
# Substring
STRING="Hello World"
echo ${STRING:0:5} # Hello
echo ${STRING:6} # World
# Replace text
echo ${STRING//World/Linux} # Hello Linux
# Remove pattern
echo ${STRING%World} # HelloPractical Examples
Database Configuration
# Store in .bashrc or .profile
export DB_HOST="localhost"
export DB_PORT="5432"
export DB_USER="postgres"
export DB_PASSWORD="secret" # Not recommended for sensitive data!
# Better: Read from file
if [ -f ~/.db_config ]; then
source ~/.db_config
fiPython Virtual Environment
# .bashrc setup
export VENV_PATH="$HOME/.venvs"
# Function to activate venv
venv() {
if [ -d "$VENV_PATH/$1" ]; then
source "$VENV_PATH/$1/bin/activate"
else
echo "Virtual environment not found"
fi
}
# Usage
venv myprojectDevelopment Environment
# Development setup in .bashrc
export DEV_HOME="$HOME/development"
export PROJECT_PATH="$DEV_HOME/myproject"
alias dev='cd $PROJECT_PATH'
alias start-dev='npm start'
alias build='npm run build'
# Color output for specific commands
export LS_COLORS="di=1;34:*.js=0;33:*.json=0;33"Best Practices
- Use Meaningful Names - Variables should be self-documenting
- Export Carefully - Only export necessary variables
- Quote Values - Always quote variable values
- Use ${} Syntax - More reliable than $
- Avoid Spaces - Don't put spaces around =
- Document Variables - Comment on purpose and usage
- Keep Sensitive Data Safe - Never hardcode passwords
- Backup Configurations - Version control .bashrc and .profile
- Test Changes - Source files in new shell before committing
- Regular Review - Clean up unused variables periodically
Summary
Environment variables are crucial for Linux system configuration:
- Common variables like PATH, HOME, USER control system behavior
- env and printenv display all or specific variables
- export makes variables available to child processes
- Shell configuration files (.bashrc, .profile) persist variables
- Variable expansion enables dynamic script behavior
- Proper management enables flexible, configurable systems
Master these concepts for effective Linux administration and scripting.