Linux and Bash course menu
Linux Environment Variables and PATH Explained
Set shell and environment variables with export, understand PATH, make settings permanent in .bashrc, create aliases, and keep secrets out of your commands.
On this page
An environment variable is a named value that programs can read. Programs use them for settings such as the language, your home folder, or a database address.
See variables#
echo $HOME
echo $USER
printenv SHELL
env | grep -c ./home/asha
asha
/bin/bash
10env or printenv lists everything. By convention, names are in capitals.
Shell variables and environment variables#
A plain assignment creates a shell variable, which child programs cannot see. export makes it an environment variable:
CITY=Hyderabad
bash -c 'echo "Child sees: [$CITY]"'
export CITY
bash -c 'echo "Child sees: [$CITY]"'Child sees: []
Child sees: [Hyderabad]There must be no spaces around =. For a single command, put the value in front of it:
GREETING=Namaste bash -c 'echo $GREETING'
echo "After: [$GREETING]"Namaste
After: []This is how you pass settings to a program, as in PORT=3000 node app.js.
PATH#
When you type ls, the shell looks through the folders listed in PATH, in order, and runs the first match:
echo $PATH | tr ':' '\n' | head -n 3
which python3/usr/local/bin
/usr/bin
/bin
/usr/bin/python3"Command not found" often means that the program's folder is not in PATH. Add your own folder to the front:
mkdir -p ~/bin
echo 'echo "Hello from my tool"' > ~/bin/mytool
chmod +x ~/bin/mytool
export PATH="$HOME/bin:$PATH"
mytool
which mytoolHello from my tool
/home/asha/bin/mytoolMake it permanent#
Variables disappear when the shell closes. Add them to ~/.bashrc, which runs for each new interactive shell:
echo 'export EDITOR=nano' >> ~/.bashrc
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.bashrc
tail -n 2 ~/.bashrcexport EDITOR=nano
export PATH="$HOME/bin:$PATH"Then load it into the current shell:
source ~/.bashrcAliases#
An alias is a short name for a command. Add these to ~/.bashrc too:
alias ll='ls -lah'
alias gs='git status'
alias ..='cd ..'Run alias to list them, and unalias name to remove one.
Secrets#
Do not type passwords directly on the command line, because they are saved in your history and may be visible in process lists. For development, keep them in a .env file, which you add to .gitignore:
echo 'API_KEY=example-not-real' > .env
chmod 600 .env
set -a
source .env
set +a
bash -c 'echo "Key length: ${#API_KEY}"'Key length: 16set -a exports everything assigned until set +a.
Common mistakes#
Practice#
Practice exercise
Run printenv APP_MODE so that it prints production, without exporting the variable, then show that APP_MODE is empty afterwards.
Show solution
APP_MODE=production printenv APP_MODE
echo "[$APP_MODE]"production
[]Key takeaway#
Next: Processes.
Finished this lesson?