Skip to main content

Configuring the Linux Shell Environment

Master Linux environment variables, PATH, dotfiles, shell startup file order and direnv for consistent production and development environments.

30 Terms

Overview and What You Will Learn

The Linux environment is the set of variables, such as PATH, EDITOR and LANG, that every process inherits from its parent and that decide how commands behave. These variables come from shell startup files, so which file you edit decides whether a change reaches interactive shells, scripts, cron jobs or services. This lab assumes a Debian or Ubuntu server and, for steps 2 and 6, a systemd service called payment-api. Substitute your own service name.

  • Telling shell variables apart from environment variables
  • Tracing which startup files each kind of shell reads
  • Managing PATH safely for interactive shells, scripts and services
  • Writing modular, idempotent dotfiles that are safe to source repeatedly
  • Using direnv for per-project environments
  • Configuring environment variables for all users and for systemd services

Why This Matters in Production

Environment drift is a quiet source of production bugs, because the same command can resolve to different programs on different machines. Picture a DevOps engineer at a company like Zerodha whose deployment script calls python3 for validation. On their laptop it resolves to Python 3.11, but on the server a different PATH makes it resolve to Python 3.6, and the script silently produces different results. Knowing where environment settings come from lets you diagnose that in minutes and prevent it with explicit configuration.

Core Principles

A shell variable exists only inside the current shell, while an environment variable is exported and copied into every child process the shell starts. Which startup files a shell reads depends on whether it is a login shell, whether it is interactive, and what started it, and that decides where a setting belongs.

flowchart TD A["/etc/profile
system-wide"]:::slate --> B["/etc/profile.d/*.sh
drop-in config"]:::slate B --> C["First file found:
~/.bash_profile, ~/.bash_login,
or ~/.profile"]:::tool C -->|must source it| D["~/.bashrc
interactive config"]:::ok classDef slate fill:#475569,color:#FFFFFF classDef tool fill:#326CE5,color:#FFFFFF classDef ok fill:#10B981,color:#FFFFFF
Context What it reads
Login shell (SSH, su -, bash -l) /etc/profile, its profile.d drop-ins, then the first of the three user files above
Interactive non-login shell (new terminal tab) ~/.bashrc (and /etc/bash.bashrc on Debian and Ubuntu)
Script run by bash Nothing, unless BASH_ENV names a file
Cron job Nothing, and it runs under /bin/sh with a minimal environment
systemd service Nothing, only its own Environment= and EnvironmentFile= settings

Two details cause most surprises. Bash reads only the first of ~/.bash_profile, ~/.bash_login and ~/.profile, and none of them reads ~/.bashrc unless the file does so itself. A command run directly through SSH, such as ssh host command, is a special case where bash also reads ~/.bashrc.

Detailed Step-by-Step Practical Lab

Step 1 - Compare Shell and Environment Variables
Bash
MY_VAR="hello"
echo $MY_VAR
bash -c 'echo $MY_VAR' # empty: child processes do not inherit it
# An exported variable is inherited by children
export MY_VAR="hello"
bash -c 'echo $MY_VAR' # hello
# Show only the environment, then everything the shell knows
env
set | head -30
# Confirm a variable is exported
export -p | grep MY_VAR # declare -x MY_VAR="hello"
# Set a variable for one command only
NODE_ENV=staging node server.js
# Remove a variable, and make another one read-only for this shell
unset MY_VAR
readonly DB_HOST="10.0.2.100"
DB_HOST="other" # Error: readonly variable
Step 2 - Trace the Startup Files

Find out what kind of shell you are in, then trace the files a login shell reads:

Bash
echo $0 # -bash is a login shell, bash is not
shopt login_shell # login_shell on (or off)
# List the files read by a login shell (output varies by distribution)
PS4='+${BASH_SOURCE[0]}:${LINENO} ' bash -l -x -c exit 2>&1 \
| grep -oE '^\++[^: ]+' | tr -d '+' | awk '!seen[$0]++'

See what cron actually gives a job. Add this line with crontab -e, wait a minute, compare, then remove the line:

Bash
# crontab entry (note: no date formatting, because % is special in crontab):
# * * * * * env > /tmp/cron-env.txt 2>&1
diff <(env | sort) <(sort /tmp/cron-env.txt)

See what a systemd service receives:

Bash
sudo systemctl show -p Environment -p EnvironmentFiles payment-api
PID=$(systemctl show payment-api -p MainPID --value)
sudo xargs -0 -n1 -a /proc/$PID/environ
Step 3 - Manage PATH Safely
Bash
echo $PATH
# /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Prepend: your tools win over system ones
export PATH="/opt/mytools/bin:$PATH"
# Append: a fallback if nothing earlier matches
export PATH="$PATH:/opt/mytools/bin"
# See every match in search order, including aliases and functions
type -a python3
command -v node # empty output means node is not on PATH

Add a directory for all users with a profile.d drop-in. It affects login shells only, not systemd services or cron:

Bash
sudo tee /etc/profile.d/custom-tools.sh > /dev/null << 'EOF'
export PATH="/opt/mytools/bin:$PATH"
EOF
Tip

Use type -a command instead of which. It lists every match in PATH order, shows whether a name is an alias, function or builtin, and works in any bash session.

Step 4 - Write Modular, Idempotent Dotfiles

Never overwrite an existing ~/.bashrc. Back it up, add a small loader once, and keep your own settings in separate files:

Bash
cp ~/.bashrc ~/.bashrc.bak
grep -q 'bashrc.d' ~/.bashrc || cat >> ~/.bashrc << 'EOF'
# Load modular config from ~/.bashrc.d
if [ -d "$HOME/.bashrc.d" ]; then
for f in "$HOME"/.bashrc.d/*.sh; do
[ -r "$f" ] && . "$f"
done
fi
EOF
# Confirm login shells reach ~/.bashrc (Ubuntu's ~/.profile already does)
grep -n bashrc ~/.profile ~/.bash_profile 2>/dev/null
Common Mistake

Creating a ~/.bash_profile on a system that only had ~/.profile. Bash then reads ~/.bash_profile first and silently ignores ~/.profile, so settings disappear from login shells. If you create it, make it source ~/.profile and ~/.bashrc.

Put variables, PATH and history settings in one file. The path_prepend helper adds a directory only once, so sourcing the file twice does not grow PATH:

Bash
mkdir -p ~/.bashrc.d
cat > ~/.bashrc.d/10-environment.sh << 'EOF'
export EDITOR="vim"
export PAGER="less"
export LANG="en_US.UTF-8"
path_prepend() {
case ":$PATH:" in
*":$1:"*) ;;
*) PATH="$1:$PATH" ;;
esac
}
path_prepend "$HOME/bin"
path_prepend "$HOME/.local/bin"
export PATH
export HISTSIZE=10000
export HISTFILESIZE=20000
export HISTCONTROL=ignoreboth:erasedups
shopt -s histappend
# Write each command to the history file as it runs, only once
case "$PROMPT_COMMAND" in
*"history -a"*) ;;
*) PROMPT_COMMAND="history -a${PROMPT_COMMAND:+; $PROMPT_COMMAND}" ;;
esac
EOF

Put aliases, functions and the prompt in a second file:

Bash
cat > ~/.bashrc.d/20-devops.sh << 'EOF'
alias ll='ls -lah'
alias ..='cd ..'
alias grep='grep --color=auto'
alias k='kubectl'
alias kgp='kubectl get pods'
alias dps='docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"'
alias dlogs='docker logs -f --tail 100'
# Search a service's log: loggrep PATTERN [service]
loggrep() {
grep -E "$1" "/var/log/${2:-app}/app.log"
}
# Open an SSH tunnel through the bastion: tunnel LOCAL_PORT HOST [REMOTE_PORT]
tunnel() {
local local_port="$1" remote_host="$2" remote_port="${3:-$1}"
ssh -fN -L "${local_port}:${remote_host}:${remote_port}" bastion
echo "Tunnel open: localhost:${local_port} -> ${remote_host}:${remote_port}"
}
# Prompt: user@host:dir (git branch) $
git_branch() {
local b
b=$(git branch --show-current 2>/dev/null) && [ -n "$b" ] && printf ' (%s)' "$b"
}
PS1='\[\e[32m\]\u@\h\[\e[m\]:\[\e[34m\]\w\[\e[m\]$(git_branch)\$ '
EOF
source ~/.bashrc
type -a ll
Remember

Changes to a dotfile reach the current shell only after source ~/.bashrc or a new terminal. Running bash starts a sub-shell that reads the file, so type exit to return to your original shell.

Step 5 - Per-Project Environments with direnv

direnv loads and unloads environment variables as you enter and leave a directory, which suits projects with different runtimes, credentials or database URLs.

Bash
sudo apt install direnv
echo 'eval "$(direnv hook bash)"' >> ~/.bashrc
source ~/.bashrc
cd /opt/payment-api
cat > .envrc << 'EOF'
export NODE_ENV=development
export PORT=4000
export DATABASE_URL="postgresql://localhost:5432/payment_dev"
export LOG_LEVEL=debug
# Load KEY=VALUE secrets from a file that is never committed
dotenv_if_exists .env.local
EOF
# direnv refuses to load a new .envrc until you approve it
direnv allow .
echo $NODE_ENV # development
cd ~
echo $NODE_ENV # empty: the previous environment is restored
echo ".env.local" >> /opt/payment-api/.gitignore
Security

Never commit secrets to Git, and that includes dotfile repositories. Commit .envrc only with non-sensitive values, keep secrets in an ignored .env.local, and remember that anyone who pulls a changed .envrc must run direnv allow again after reading it.

Step 6 - Environment for All Users and for Services

/etc/environment is a plain KEY=VALUE file read by PAM for login sessions. It has no shell syntax and systemd services do not read it. Back it up and append, because on Ubuntu it already holds the system PATH:

Bash
cat /etc/environment
sudo cp /etc/environment /etc/environment.bak
echo 'EDITOR=vim' | sudo tee -a /etc/environment
# Set the time zone with its own tool, not an environment variable
sudo timedatectl set-timezone Asia/Kolkata

For a systemd service, put variables in an EnvironmentFile. systemd reads it as root before starting the service, so the file can stay private:

Bash
sudo mkdir -p /etc/payment-api
sudo tee /etc/payment-api/env > /dev/null << 'EOF'
NODE_ENV=production
PORT=4000
DB_HOST=10.0.2.100
DB_PORT=5432
LOG_LEVEL=info
EOF
sudo chown root:root /etc/payment-api/env
sudo chmod 600 /etc/payment-api/env

Attach it with a drop-in, then restart so the service picks it up:

Bash
sudo systemctl edit payment-api
INI
[Service]
EnvironmentFile=/etc/payment-api/env
Bash
sudo systemctl daemon-reload
sudo systemctl restart payment-api
sudo systemctl show -p EnvironmentFiles payment-api
PID=$(systemctl show payment-api -p MainPID --value)
sudo xargs -0 -n1 -a /proc/$PID/environ | grep -E 'NODE_ENV|PORT'
Common Mistake

Setting variables in ~/.bashrc and expecting cron jobs or services to see them. ~/.bashrc is read only by interactive bash. Cron needs variables set in the crontab or the script, and services need Environment= or EnvironmentFile= in their unit.

Production Best Practices & Common Pitfalls

Scenario Wrong Correct
Extra PATH for all login users Edit /etc/environment Add a /etc/profile.d/*.sh drop-in
Service configuration Hardcode values in the unit file EnvironmentFile owned by root with mode 600
Project-specific variables Export them globally in ~/.bashrc A per-project .envrc with direnv
Secrets Put them in dotfiles or commit them Load from a secrets manager at runtime
Cron PATH problems Assume it matches your shell Set PATH= in the crontab and use absolute paths
Repeated sourcing Append to PATH unconditionally A guarded helper such as path_prepend
  • Avoid setting LC_ALL globally. It overrides every other locale variable and breaks tools when the locale is not generated, so set LANG and let individual commands override.
  • Keep non-interactive needs out of ~/.bashrc. Debian and Ubuntu return early from it for non-interactive shells, so anything a script needs must live elsewhere.
  • Restart after changing service variables. A running process keeps the environment it started with.

Quick Reference & Troubleshooting Commands

Task Command
Show environment variables env or printenv
Export a variable export VAR=value
Show which binary runs type -a cmd
Check shell type shopt login_shell
Apply dotfile changes source ~/.bashrc
Read a process's environment sudo xargs -0 -n1 -a /proc/PID/environ
Show service environment settings systemctl show -p Environment -p EnvironmentFiles SERVICE
Approve a direnv file direnv allow .
Check direnv state direnv status

Resources

Explore More in Linux Shell Scripting and Automation

All 6 Topics

Frequently Asked Questions

Is Configuring the Linux Shell Environment free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Configuring the Linux Shell Environment topic cover?

Master Linux environment variables, PATH, dotfiles, shell startup file order and direnv for consistent production and development environments.

Found a mistake, an outdated step or a broken link?