Linux Environment Variables: export, PATH, and Shell Profile Loading Order
The export boundary between shell and environment variables, why PATH order and the command hash cache decide which binary runs, and the exact file order bash reads for login, interactive, and non-interactive shells.

Quick Summary
An environment variable is a string in a process's environment block that every child process inherits. A shell variable is a name in the shell's own variable table. The only difference between the two is the export attribute: FOO=bar creates a shell variable that dies with the shell, while export FOO=bar copies it into the environment of every process the shell starts after that point. Almost every "it works in my shell but not in the service" bug is one of those two facts.
PATH is the most consequential environment variable, a colon-separated list of directories searched left to right by execvp and by the shell's command lookup. Bash also caches the resolved path of each command it has run in a hash table, so moving a binary or installing a new one can keep executing the old copy until you run hash -r. /usr/local/bin is normally ahead of /usr/bin on Linux, which is how a locally installed tool shadows the distribution's.
Profiles decide which of these assignments exist when a shell starts. Bash reads different files for a login shell, an interactive non-login shell, and a non-interactive script, and that order is why an alias works in a terminal but not over SSH. This guide covers the syntax, the export boundary, PATH and its hash cache, the exact file order for bash, and the places where service managers skip all of it.
Basic Syntax & Signature
# Shell variable only: not inherited by children
GREETING=hello
# Environment variable: inherited by every child process started after this
export GREETING=hello
export DB_HOST=db.internal DB_PORT=5432 # multiple in one export
# Declare and export in one step
declare -x APP_ENV=production
# Read
echo "$GREETING"
printenv GREETING # environment only
env | grep '^PATH=' # environment as the child would see it
set | grep '^GREETING=' # every shell variable, including non-exported
# Remove
unset GREETING
# One-shot assignment: exported to that command only, does not persist
GREETING=hi env | grep GREETING
# GREETING=hi /usr/bin/env -> shows GREETING
# after the command, the shell's GREETING is unchanged
# Run with an empty environment
env -i PATH=/usr/bin:/bin /bin/sh -c 'env'
# Run a command with one variable removed
env -u AWS_PROFILE aws s3 ls# PATH manipulation: prepend, append, and de-duplicate safely
export PATH="$HOME/.local/bin:$PATH" # prepend, highest priority
export PATH="$PATH:/opt/app/bin" # append, lowest priority
# Inspect it one entry per line
printf '%s\n' "${PATH//:/$'\n'}"
# Check what a name resolves to, including aliases and functions
type -a python3
command -v python3 # scripts: command -v is portable, no error output
which python3 # external tool; does not see aliases, skips functions
hash -r # clear bash's command path cache
# Detect the shell kind at runtime
shopt -q login_shell && echo "login shell"
[[ $- == *i* ]] && echo "interactive"
echo "$0" # login shells are usually started with a leading '-'The files bash reads, in order:
Login shell (ssh host, tty login, bash -l, su - user)
1. /etc/profile
2. /etc/profile.d/*.sh (loop run by /etc/profile; Debian, RHEL)
3. ~/.bash_profile | ~/.bash_login | ~/.profile (first one that exists)
Interactive non-login shell (xterm, tmux, desktop terminal, bash -i)
1. /etc/bash.bashrc (Debian) or /etc/bashrc (RHEL), if compiled in
2. ~/.bashrc
Non-interactive shell (bash script.sh, bash -c '...')
1. $BASH_ENV, if set, is sourced
2. ~/.bashrc, if bash detects its stdin is a network connection (sshd/rshd)
Every bash process, before any of the above
- exported variables inherited from the parent process/etc/environment is not a bash file. It is read by PAM (pam_env) at login, has no shell syntax (no export, no $()), and affects sessions started after it changes, which is why editing it has no effect on the terminal you already have open.
Key Comparison Table
| Mechanism | Written by | Shell syntax | When it applies |
|---|---|---|---|
VAR=value | Shell | Bash/POSIX | Current shell only, not exported |
export VAR=value | Shell | Bash/POSIX | Current shell and all later children |
VAR=value cmd | Shell | Bash/POSIX | That one command's environment |
~/.bashrc | User | Bash | Interactive non-login; ssh commands |
~/.bash_profile | User | Bash | Login shells only (first of three) |
~/.profile | User | POSIX sh | Login shells of sh, dash, bash, some GUI sessions |
/etc/profile + /etc/profile.d/*.sh | Root | POSIX | Every login shell, all users |
/etc/environment | Root | None (KEY=VALUE) | PAM sessions at login, GUI included |
systemd Environment= | Root | None | Units that declare it |
EnvironmentFile= | Root | None | Units that declare it |
Dockerfile ENV | Image author | None | Container processes, not build RUN of earlier layers |
sudo VAR=value cmd | User | Bash | Only if sudoers allows the variable |
| Question | Command | Notes |
|---|---|---|
| Is it exported? | declare -p GREETING | Shows the -x flag when exported |
| What will a child see? | env | Only the exported environment |
| Which copy of a command wins? | type -a name | All matches, in PATH order |
Practical Edge Cases & Deep Dives
1. The export boundary, and why a sourced file behaves differently
# setup.sh
APP_ENV=production$ bash setup.sh
$ echo "$APP_ENV" # empty: the child's variables are gone with it
$ source setup.sh # same shell, variables now exist
$ echo "$APP_ENV" # productionA script run with bash setup.sh gets a copy of the parent environment and its own variable table; nothing it assigns flows back. source script.sh (or . script.sh) executes the lines in the current shell, which is why it can set PATH or cd, and also why a set -e or a trap inside a sourced file leaks into your session. When a sourced file must export, it has to say export explicitly on each name it wants to hand down — the act of sourcing does not make the shell variable an environment variable.
2. PATH order, shadowing, and the hash cache
$ type -a kubectl
kubectl is /usr/local/bin/kubectl
kubectl is /usr/bin/kubectl
$ /usr/bin/kubectl version --client # bypass the shadowing copyTwo copies of a binary are the common outcome of a package upgrade that leaves the old one in /usr/bin while the new one lands in /usr/local/bin. PATH decides which wins, and type -a shows all of them. The trap is bash's hash table: after the first successful lookup, bash reuses the remembered full path.
$ hash -t kubectl
/usr/bin/kubectl
$ sudo install -m 0755 ./kubectl /usr/local/bin/kubectl
$ kubectl version --client # still /usr/bin/kubectl
$ hash -r # forgets every cached path
$ kubectl version --client # now the /usr/local/bin copyPATH entries that do not exist, empty entries (which mean the current directory), and duplicate entries are all legal and all slow down lookup. A defensive prepend guards against duplicates:
case ":$PATH:" in
*":$HOME/.local/bin:"*) ;;
*) export PATH="$HOME/.local/bin:$PATH" ;;
esacUsing a relative or empty entry (., ::, a trailing :) means a command can be resolved to a file in whatever directory you happen to be in — the classic way a downloaded script in /tmp gets executed instead of /usr/bin.
3. Login shell versus interactive shell: the classic missing PATH over SSH
# Works locally, fails over ssh:
$ ssh host 'python3 -m app'
bash: python3: command not foundssh host command starts a non-interactive shell, so ~/.bash_profile is not read; bash sources ~/.bashrc in that case (because it detects a network connection as stdin), and only then if ~/.bashrc has not been short-circuited by an early return. That early return is the actual bug in most setups:
# ~/.bashrc — correct guard, non-interactive execution stops before exports
case $- in
*i*) ;;
*) return;;
esacThat guard is right for aliases and prompts, and it is exactly why environment exports must not live after it. Put the network-safe part (PATH, language variables, API base URLs) above the guard, or in a separate ~/.profile.d line sourced by both.
# ~/.profile or ~/.bash_profile — one canonical place for PATH
export PATH="$HOME/.local/bin:$PATH"
# ~/.bashrc — source the login file so interactive shells agree with login shells
[ -f "$HOME/.profile" ] && . "$HOME/.profile"Also check sshd itself: PermitUserEnvironment no (the default) means ~/.ssh/environment is ignored, and non-interactive sessions get the environment built by PAM and sshd, not by your shell profile.
4. Profiles are not read by services, containers, or cron
# /etc/systemd/system/app.service
[Service]
Environment=APP_ENV=production LOG_LEVEL=info
EnvironmentFile=/etc/app/app.env
ExecStart=/opt/app/bin/server# /etc/app/app.env — plain KEY=VALUE, no export, no quotes around multiword
APP_ENV=production
DATABASE_URL=postgres://app:secret@db:5432/appsystemd starts units with an empty environment plus what the unit declares, so ~/.bashrc might as well not exist. Docker behaves the same way: ENV in the image and -e/--env-file at run time are the environment, and a shell inside the container inherits only those until it reads its own profile (which a minimal image usually does not ship). cron runs commands with SHELL=/bin/sh and a PATH of roughly /usr/bin:/bin.
# The one reliable diagnostic for all three: ask the actual process
systemctl show -p Environment app.service
tr '\0' '\n' < /proc/$(pgrep -f /opt/app/bin/server)/environ
docker exec app env/proc/<pid>/environ is the process's environment as it was at exec time — note that editing a variable later in a shell does not rewrite it, which is why the file can disagree with what the process actually sees.
5. Secrets do not belong in the environment
Anything exported is readable by ps e, in /proc/<pid>/environ, in crash dumps, and by every child the app spawns. For anything with real value, use a 0600 file read by the process instead (EnvironmentFile= in systemd is fine if its permissions are restricted), and remember that sudo resets the environment by default, so sudo -E and sudo VAR=value only work when sudoers allows them.
Common Runtime & Configuration Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Works in terminal, empty over SSH | Variable exported from ~/.bashrc below the interactive guard, or only in ~/.bash_profile | Move exports above the guard or into a shared file |
command not found in a script | Non-interactive shell has no profile; PATH is minimal | Set PATH in the script or the unit |
| New binary ignored | Bash hash cache holds the old path | hash -r |
| Two versions, wrong one runs | PATH order, old copy still present | type -a, remove or reorder |
Edited /etc/environment, no effect | PAM reads it at login only, and it has no shell syntax | Log out and back in, or use a profile file |
Variable empty in sudo command | env_reset default | sudo -E or env_keep in sudoers |
| Service sees no variables | systemd/Docker do not read profiles | Environment=/EnvironmentFile= |
Secrets visible in ps e | Secret exported into the environment | Read a 0600 file instead |
source leaks set -e or a trap | Sourced code runs in your shell | Execute it instead |
The whole model fits in three sentences: assignment defines a name in the current shell, export copies it to the environment that children inherit, and a profile file is only the script that performs those assignments when a particular kind of shell starts. Once the shell kind, the file, and the export step are each known, an environment bug stops being mysterious — and stopping at the actual process's environment (/proc/<pid>/environ, systemctl show, docker exec env) is faster than reading startup files and guessing.
Try matching browser tools
All toolsSmall utilities that fit Linux work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Linux guides
All Linux guidesBash Indexed Arrays, Associative Maps, and Parameter Expansion
Quoting decides whether an array stays a list, and the expansion operators replace most external text tools. Includes set -u, mapfile, namerefs, and the bash 3.2 differences that break scripts on macOS.
Parsing JSON and YAML in Shell Pipelines with jq and yq
jq is a filter language, not a pretty-printer. The operators that do the work, --arg versus string interpolation, in-place YAML edits, and how to tell which yq is installed before writing a command.
Linux Memory, Swap, the OOM Killer, vmstat, and sysctl Tuning
MemAvailable versus used, the vmstat columns that prove thrashing, how the OOM killer picks its victim, and the sysctl keys that belong in /etc/sysctl.d instead of a one-off command.
Linux Firewalls: ufw, iptables, and nftables Rules and Persistence
First-match ordering, stateful filtering, and persistence: the three ideas behind every Linux firewall. Plus why Docker-published ports ignore ufw and how DOCKER-USER closes them.
More in Linux
All Linux guidesThe guides filed next to this one in Linux, in library order.