SyntaxStudy
Sign Up
Linux / Bash Environment Variables and the Shell Environment
Linux / Bash Beginner 1 min read

Environment Variables and the Shell Environment

Environment variables are named string values that exist in a process environment and are inherited by child processes. They configure program behaviour without requiring code changes. The `env` command lists all current environment variables. `printenv VAR` prints a specific variable. Inside a script or interactive shell, `echo $VAR` expands the variable value. Variables defined in a shell session without `export` are shell-local variables — they exist in the current shell but are not passed to child processes (subshells, scripts, programs). The `export` command marks a variable for export. You can combine assignment and export in one step: `export MY_VAR=value`. To permanently set a variable for all sessions, add the export to your shell configuration file. Common important environment variables include `HOME` (home directory path), `USER` and `LOGNAME` (current username), `SHELL` (path to current shell), `TERM` (terminal type), `LANG` and `LC_*` (locale settings), `EDITOR` and `VISUAL` (default text editors), `PAGER` (default pager program), and `TMPDIR` (temporary directory path).
Example
# List all environment variables
env
printenv

# Print a specific variable
printenv HOME
echo $HOME
echo $USER
echo $SHELL

# Assign a shell-local variable (NOT exported)
MY_VAR="hello"
bash -c 'echo $MY_VAR'     # Empty — not exported

# Export a variable (available to child processes)
export MY_VAR="hello"
bash -c 'echo $MY_VAR'     # Prints: hello

# Export and assign in one step
export API_URL="https://api.example.com"

# Check if a variable is set
if [[ -n "${MY_VAR:-}" ]]; then
    echo "MY_VAR is set to: $MY_VAR"
fi

# Temporarily override a variable for one command
LANG=C ls --help

# Show common important variables
echo "Home:    $HOME"
echo "User:    $USER"
echo "Shell:   $SHELL"
echo "Editor:  ${EDITOR:-not set}"
echo "Term:    $TERM"
echo "Path:    $PATH"

# Unset a variable
unset MY_VAR

# Store variable in a script-friendly way using .env file
# cat .env:
# DB_HOST=localhost
# DB_PORT=5432

# Source (load) the .env file into current shell
# source .env   OR   . .env