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
PATHsafely for interactive shells, scripts and services - Writing modular, idempotent dotfiles that are safe to source repeatedly
- Using
direnvfor 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.
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
MY_VAR="hello"echo $MY_VARbash -c 'echo $MY_VAR' # empty: child processes do not inherit it # An exported variable is inherited by childrenexport MY_VAR="hello"bash -c 'echo $MY_VAR' # hello # Show only the environment, then everything the shell knowsenvset | head -30 # Confirm a variable is exportedexport -p | grep MY_VAR # declare -x MY_VAR="hello" # Set a variable for one command onlyNODE_ENV=staging node server.js # Remove a variable, and make another one read-only for this shellunset MY_VARreadonly DB_HOST="10.0.2.100"DB_HOST="other" # Error: readonly variableStep 2 - Trace the Startup Files
Find out what kind of shell you are in, then trace the files a login shell reads:
echo $0 # -bash is a login shell, bash is notshopt 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:
# 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:
sudo systemctl show -p Environment -p EnvironmentFiles payment-api PID=$(systemctl show payment-api -p MainPID --value)sudo xargs -0 -n1 -a /proc/$PID/environStep 3 - Manage PATH Safely
echo $PATH# /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin # Prepend: your tools win over system onesexport PATH="/opt/mytools/bin:$PATH" # Append: a fallback if nothing earlier matchesexport PATH="$PATH:/opt/mytools/bin" # See every match in search order, including aliases and functionstype -a python3command -v node # empty output means node is not on PATHAdd a directory for all users with a profile.d drop-in. It affects login shells only, not systemd services or cron:
sudo tee /etc/profile.d/custom-tools.sh > /dev/null << 'EOF'export PATH="/opt/mytools/bin:$PATH"EOFTipUse
type -a commandinstead ofwhich. It lists every match inPATHorder, 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:
cp ~/.bashrc ~/.bashrc.bak grep -q 'bashrc.d' ~/.bashrc || cat >> ~/.bashrc << 'EOF' # Load modular config from ~/.bashrc.dif [ -d "$HOME/.bashrc.d" ]; then for f in "$HOME"/.bashrc.d/*.sh; do [ -r "$f" ] && . "$f" donefiEOF # Confirm login shells reach ~/.bashrc (Ubuntu's ~/.profile already does)grep -n bashrc ~/.profile ~/.bash_profile 2>/dev/nullCommon MistakeCreating a
~/.bash_profileon a system that only had~/.profile. Bash then reads~/.bash_profilefirst and silently ignores~/.profile, so settings disappear from login shells. If you create it, make it source~/.profileand~/.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:
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=10000export HISTFILESIZE=20000export HISTCONTROL=ignoreboth:erasedupsshopt -s histappend # Write each command to the history file as it runs, only oncecase "$PROMPT_COMMAND" in *"history -a"*) ;; *) PROMPT_COMMAND="history -a${PROMPT_COMMAND:+; $PROMPT_COMMAND}" ;;esacEOFPut aliases, functions and the prompt in a second file:
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 ~/.bashrctype -a llRememberChanges to a dotfile reach the current shell only after
source ~/.bashrcor a new terminal. Runningbashstarts a sub-shell that reads the file, so typeexitto 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.
sudo apt install direnvecho 'eval "$(direnv hook bash)"' >> ~/.bashrcsource ~/.bashrc cd /opt/payment-apicat > .envrc << 'EOF'export NODE_ENV=developmentexport PORT=4000export DATABASE_URL="postgresql://localhost:5432/payment_dev"export LOG_LEVEL=debug # Load KEY=VALUE secrets from a file that is never committeddotenv_if_exists .env.localEOF # direnv refuses to load a new .envrc until you approve itdirenv allow .echo $NODE_ENV # development cd ~echo $NODE_ENV # empty: the previous environment is restored echo ".env.local" >> /opt/payment-api/.gitignoreSecurityNever commit secrets to Git, and that includes dotfile repositories. Commit
.envrconly with non-sensitive values, keep secrets in an ignored.env.local, and remember that anyone who pulls a changed.envrcmust rundirenv allowagain 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:
cat /etc/environmentsudo cp /etc/environment /etc/environment.bakecho 'EDITOR=vim' | sudo tee -a /etc/environment # Set the time zone with its own tool, not an environment variablesudo timedatectl set-timezone Asia/KolkataFor a systemd service, put variables in an EnvironmentFile. systemd reads it as root before starting the service, so the file can stay private:
sudo mkdir -p /etc/payment-apisudo tee /etc/payment-api/env > /dev/null << 'EOF'NODE_ENV=productionPORT=4000DB_HOST=10.0.2.100DB_PORT=5432LOG_LEVEL=infoEOFsudo chown root:root /etc/payment-api/envsudo chmod 600 /etc/payment-api/envAttach it with a drop-in, then restart so the service picks it up:
sudo systemctl edit payment-api[Service]EnvironmentFile=/etc/payment-api/envsudo systemctl daemon-reloadsudo systemctl restart payment-api sudo systemctl show -p EnvironmentFiles payment-apiPID=$(systemctl show payment-api -p MainPID --value)sudo xargs -0 -n1 -a /proc/$PID/environ | grep -E 'NODE_ENV|PORT'Common MistakeSetting variables in
~/.bashrcand expecting cron jobs or services to see them.~/.bashrcis read only by interactive bash. Cron needs variables set in the crontab or the script, and services needEnvironment=orEnvironmentFile=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_ALLglobally. It overrides every other locale variable and breaks tools when the locale is not generated, so setLANGand 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 |