Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Environment Variables Command Guide: Configuration Your Shell Carries

Environment variables are named values stored in your shell’s environment — configuration that every command it starts can read, which is why they’re the backbone of shell scripting and system configuration.


What is an Environment Variable?

An environment variable is a (name, value) pair attached to your current shell process. Every command your shell launches inherits a copy of these variables, and commands can read them to configure their behavior.

They’re everywhere:

  • HOME — where your home directory is.
  • USER — who you are.
  • PATH — where the shell looks for commands (covered in depth on its own page, $PATH and the Command Lookup Path).
  • LANG / LC_* — locale settings: language, character encoding, number formats.
  • SHELL — your login shell.
  • PS1 — the prompt string itself (the text you see before your commands).

By convention, names are UPPERCASE with underscores: EDITOR, http_proxy, GIT_AUTHOR_NAME. The all-caps style is convention, not a rule — some system variables (like http_proxy) are lowercase, and case does matter: Path and PATH are different variables.

Why Learn Environment Variables?

  • They configure the tools you already use. Your editor (EDITOR), your browser (BROWSER), your locale (LANG) — all driven by variables.
  • They make scripts configurable. A script that reads DEST_DIR instead of hardcoding /backup is reusable on any machine.
  • They’re part of security. A leaked API_TOKEN environment variable is a leaked credential; knowing where secrets live (and shouldn’t) is an admin skill.
  • They’re inherited, deliberately. Understanding inheritance explains why export matters — the single most common scripting mistake is forgetting it.

Environment variables are the shell’s memory: small, global, and available to every process you start. Master them and configuration stops being mysterious.


1. Listing and Inspecting Variables

List everything

# All environment variables (exported ones)
printenv

# One variable at a time
printenv HOME
printenv PATH

# All shell variables, exported or not
set

printenv prints only exported (environment) variables; set prints every shell variable plus function definitions. To list shell variables specifically, use declare:

declare -p          # all variables, in assignment form
declare -x          # exported variables only

Inspect a single variable

echo $HOME           # /home/user
echo $SHELL          # /bin/bash
echo $0              # the name of the current shell
echo $UID            # your user ID (bash-specific)

The $ prefix is how you read a variable — without it, you’re just typing the literal word HOME.


2. Setting Variables

Shell variables (local)

NAME="Ada"
greeting="hello"          # assignment: no spaces around =

echo $NAME                # Ada
echo $greeting            # hello

Rules that trip everyone up once:

  • No spaces around =. NAME = Ada is parsed as the command NAME with arguments = and Ada — an error. NAME=Ada is an assignment.
  • Values with spaces need quotes: TITLE="Senior Engineer".
  • Variables are strings. count=5 stores 5, not a number.

Temporary variables for one command

You can set a variable that exists only for the duration of one command:

EDITOR=vim git rebase -i HEAD~3     # EDITOR set just for this rebase
LANG=C sort file.txt                # one command in the C locale
DEBUG=1 ./deploy.sh                 # one script run with debugging on

This is the cleanest way to configure a single command without changing your shell permanently — and without polluting the rest of your session.


3. Exporting: Making Variables Visible to Child Processes

A shell variable is visible to the shell only. To make it part of the environment — inherited by every command you launch — export it:

NAME="Ada"            # shell variable: children can't see this
export NAME           # promote it to the environment

# or both at once:
export EDITOR="code --wait"

Verify the difference:

MYVAR="test"
env | grep MYVAR       # nothing — not exported
export MYVAR
env | grep MYVAR       # MYVAR=test — now in the environment

This is the concept behind environment variables: export = pass to children. A variable that isn’t exported is a note to yourself; one that is exported is an instruction to every process you start.

Set a variable per command, permanently-ish

# The variable is passed to one process and never touches your shell:
GIT_PAGER=cat git log
PROMPT_COMMAND='' ./risky-script.sh

4. Removing and Modifying

unset NAME              # delete a variable entirely
unset MYVAR PATH        # delete several

# Modify the existing value:
PATH="$PATH:/opt/myapp/bin"     # append to PATH
LANG="en_US.UTF-8"              # overwrite

unset is how you clean up temporary exports and how you remove a wrongly-set variable — including, once, the classic disaster of unset PATH (see Common Pitfalls).


5. Where They Come From: Startup Files

Variables set in your terminal vanish when it closes. Persistent variables live in dotfiles that the shell reads at startup:

FileRead byTypical use
~/.profilelogin shellsPATH, LANG, one-time setup
~/.bash_profile / ~/.bash_loginbash login shellssources .profile, sets PATH
~/.bashrcinteractive bash shellsaliases, prompt, exported vars
~/.zshrcinteractive zsh shellsthe zsh equivalent of .bashrc
/etc/environmentall logins (system-wide)variables every user gets
/etc/profile + /etc/profile.d/*.shall login shellssystem-wide defaults

Example: add a personal bin directory once, and every future shell has it:

# In ~/.bashrc or ~/.zshrc:
export PATH="$HOME/.local/bin:$PATH"
export EDITOR="vim"
export HISTSIZE="10000"

The exact order these files run in is a rabbit hole — the rule of thumb: .bash_profile/.profile for login shells, .bashrc/.zshrc for interactive ones, and source ~/.bashrc to reload after editing.

Variables vs. arguments vs. config files

MechanismScopeExample
Command-line argumentone invocationgit -C /repo status
Environment variableshell + all its childrenEDITOR=vim
Config filethe tool that reads it~/.gitconfig

Environment variables sit between: broader than an argument, less structured than a config file.


6. Real-World Uses

# Configure a command per invocation:
PAGER=less man ls                 # force a pager
NO_COLOR=1 curl -s https://example.com

# Pass config into a script:
DEST=/backups/2026 ./backup.sh --verbose

# Check what a tool sees:
env | grep -i proxy               # is a proxy set?
printenv http_proxy HTTPS_PROXY   # both common spellings

# Debug your own scripts by exporting state:
export PS4='+ ${BASH_SOURCE}:${LINENO}: '
set -x                            # trace commands (see scripting page)

A few variables worth knowing by name:

  • HOME — your home directory; cd with no argument goes here.
  • PWD — the current directory (updated by cd).
  • OLDPWD — the previous directory (cd - goes back there).
  • PATH — the command search path (dedicated page).
  • LANG/LC_ALL — locale; LC_ALL=C forces the C/POSIX locale (useful for byte-precise sort, grep).
  • TMPDIR — where temporary files go.
  • SHELL — your login shell, informational only.

Common Pitfalls

1. Forgetting to export

MYVAR="hello"
./script.sh        # script sees nothing: MYVAR is a shell variable only

Export it (export MYVAR) or pass it inline (MYVAR=hello ./script.sh). This is the number-one “why doesn’t my script see my variable?” bug.

2. Spaces around =

NAME = Ada          # bash: NAME: command not found
NAME=Ada            # correct

The shell reads NAME as the command to run. No spaces, ever, in assignments.

3. Quoting values with spaces or special characters

GREETING=hello world        # wrong: 'world' becomes a command
GREETING="hello world"      # right

4. unset PATH

unset PATH           # suddenly: ls: command not found

Nothing is broken — the shell just can’t find commands anymore. Recover by setting it again (export PATH=/usr/bin:/bin) or opening a new shell. Lesson: never unset a critical variable; export PATH=... if you need to fix it.

5. Expecting variables to survive a reboot or a new terminal

Variables set in one terminal exist only in that shell. Make them persistent in ~/.bashrc / ~/.zshrc (or /etc/environment for all users) — see section 5.

6. Reading $USER/$UID instead of id

$USER and $UID are set by the shell, but they’re not authoritative on every system. For permissions work use id or whoami, which query the system directly.


PageRelationship
$PATH and the Command Lookup PathThe most important variable of all, in depth
AliasesShell shortcuts — the sibling customization tool
Shell Scripting BasicsVariables, conditionals, and loops in scripts
Bash, Sh, and ZshWhich shell you’re in, and why it matters
HistoryThe other shell memory worth configuring
RedirectionStreams and files — what exported variables configure

Environment Variables Cheatsheet

Command / SyntaxDoes what
printenvList all exported environment variables
printenv NAMEPrint one variable
setList every shell variable and function
declare -xList exported variables (bash)
NAME=valueSet a shell variable (no spaces!)
export NAMEPromote a variable to the environment
NAME=value commandSet a variable for one command only
echo $NAMERead a variable
unset NAMEDelete a variable
PATH="$PATH:/new/dir"Prepend/append to an existing variable
envSame as printenv — list the environment
env -i cmdRun cmd with an empty environment
~/.bashrc / ~/.zshrcPersistent variables for interactive shells
/etc/environmentSystem-wide variables for all logins

Environment variables configure everything from your prompt to your scripts — learn export and startup files, and the shell stops being a black box.