Environment Variables in Linux
An environment variable is a named value that the shell — and every program the shell launches — can read. They configure tools, hold credentials, set the locale, and point to important paths. Every Linux user works with them daily, even without realizing it.
See all environment variables
env # list all environment variables
printenv # same thing
printenv HOME # show one variable
Read a single variable
echo $HOME # /home/you
echo $USER # you
echo $SHELL # /bin/bash
echo $PWD # current working directory
Set a variable for the current shell
# Shell-only variable (child processes don't see it)
MY_VAR="hello"
echo $MY_VAR
# Environment variable (child processes inherit it)
export MY_VAR="hello"
Without export, the variable is local to the current shell. With export, every command you run from this shell sees it.
Set a variable for one command only
DATABASE_URL="postgres://localhost/db" python myapp.py
That sets DATABASE_URL only for that one invocation of myapp.py. The shell’s own environment doesn’t change.
Unset a variable
unset MY_VAR
Make it permanent
For your user, add the export to one of:
~/.bashrc— runs for every interactive bash shell. Most common.~/.bash_profileor~/.profile— runs at login. Use for things only needed once per session.~/.zshrc— for zsh users.
For all users system-wide:
/etc/environment— simple key=value, no shell expansion./etc/profile.d/*.sh— shell scripts that run at login.
The variables you’ll actually use
| Variable | What it does |
|---|---|
PATH |
Where the shell looks for commands |
HOME |
Your home directory |
USER |
Your username |
SHELL |
Your default shell |
EDITOR |
Default editor (used by git, visudo, etc.) |
LANG / LC_* |
Locale (language, currency, time format) |
TZ |
Timezone |
TERM |
Terminal type (affects colors, control codes) |
PS1 |
Your shell prompt |
Set EDITOR so git stops opening nano
echo 'export EDITOR=vim' >> ~/.bashrc
source ~/.bashrc
Use environment variables for secrets
Never hardcode API keys in scripts. Read them from environment:
# in your shell rc, or .env file
export OPENAI_API_KEY="sk-..."
export AWS_SECRET_ACCESS_KEY="..."
# in your script (bash)
curl -H "Authorization: Bearer $OPENAI_API_KEY" ...
For project-specific secrets, use a .env file (and .gitignore it!). Tools like direnv auto-load and unload .env files when you cd into project directories.
Common gotchas
- Changes to
~/.bashrconly apply to NEW shells. Runsource ~/.bashrcto reload. - sudo strips most environment variables for security. Use
sudo -Eto preserve them, or set them again after sudo. - cron jobs don’t have your shell’s environment. Always use absolute paths or set PATH explicitly in the cron script.
What to learn next
Next: how to discover what any command does without searching the web — man, --help, tldr.