Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~6 min readLinux
#Linux#Shell#Bash#Environment
3D illustration of exported environment blocks flowing from a shell into child processes along a PATH search chain

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

bash
# 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
bash
# 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:

text
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

MechanismWritten byShell syntaxWhen it applies
VAR=valueShellBash/POSIXCurrent shell only, not exported
export VAR=valueShellBash/POSIXCurrent shell and all later children
VAR=value cmdShellBash/POSIXThat one command's environment
~/.bashrcUserBashInteractive non-login; ssh commands
~/.bash_profileUserBashLogin shells only (first of three)
~/.profileUserPOSIX shLogin shells of sh, dash, bash, some GUI sessions
/etc/profile + /etc/profile.d/*.shRootPOSIXEvery login shell, all users
/etc/environmentRootNone (KEY=VALUE)PAM sessions at login, GUI included
systemd Environment=RootNoneUnits that declare it
EnvironmentFile=RootNoneUnits that declare it
Dockerfile ENVImage authorNoneContainer processes, not build RUN of earlier layers
sudo VAR=value cmdUserBashOnly if sudoers allows the variable
QuestionCommandNotes
Is it exported?declare -p GREETINGShows the -x flag when exported
What will a child see?envOnly the exported environment
Which copy of a command wins?type -a nameAll matches, in PATH order

Practical Edge Cases & Deep Dives

1. The export boundary, and why a sourced file behaves differently

bash
# setup.sh APP_ENV=production
bash
$ 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" # production

A 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

bash
$ type -a kubectl kubectl is /usr/local/bin/kubectl kubectl is /usr/bin/kubectl $ /usr/bin/kubectl version --client # bypass the shadowing copy

Two 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.

bash
$ 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 copy

PATH 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:

bash
case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) export PATH="$HOME/.local/bin:$PATH" ;; esac

Using 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

bash
# Works locally, fails over ssh: $ ssh host 'python3 -m app' bash: python3: command not found

ssh 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:

bash
# ~/.bashrc — correct guard, non-interactive execution stops before exports case $- in *i*) ;; *) return;; esac

That 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.

bash
# ~/.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

ini
# /etc/systemd/system/app.service [Service] Environment=APP_ENV=production LOG_LEVEL=info EnvironmentFile=/etc/app/app.env ExecStart=/opt/app/bin/server
bash
# /etc/app/app.env — plain KEY=VALUE, no export, no quotes around multiword APP_ENV=production DATABASE_URL=postgres://app:secret@db:5432/app

systemd 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.

bash
# 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

SymptomCauseFix
Works in terminal, empty over SSHVariable exported from ~/.bashrc below the interactive guard, or only in ~/.bash_profileMove exports above the guard or into a shared file
command not found in a scriptNon-interactive shell has no profile; PATH is minimalSet PATH in the script or the unit
New binary ignoredBash hash cache holds the old pathhash -r
Two versions, wrong one runsPATH order, old copy still presenttype -a, remove or reorder
Edited /etc/environment, no effectPAM reads it at login only, and it has no shell syntaxLog out and back in, or use a profile file
Variable empty in sudo commandenv_reset defaultsudo -E or env_keep in sudoers
Service sees no variablessystemd/Docker do not read profilesEnvironment=/EnvironmentFile=
Secrets visible in ps eSecret exported into the environmentRead a 0600 file instead
source leaks set -e or a trapSourced code runs in your shellExecute 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 tools

Small utilities that fit Linux work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Linux guides

More in Linux

All Linux guides

The guides filed next to this one in Linux, in library order.