Latticework

Command Palette

Search for a command to run...

Terminal / CLI

Environment Variables

12 min

Explanation

Environment variables are the shell's way of passing configuration around without hard-coding it: export NAME=value sets one, and $NAME substitutes its current value into any later command. A handful are set for you automatically — $HOME (your home directory) and $PWD (your current directory, always kept in sync by cd) are the two you'll lean on most. Using a variable instead of a literal value is what lets the exact same script work correctly across different users, machines, or environments.

export EDITOR=nano
echo "using $EDITOR"
# using nano
echo config for $EDITOR > $EDITOR.conf
cat $EDITOR.conf
# config for nano
Try it

The same three lines would create a totally different directory if APP_ENV were set to production instead — that's the entire point of using a variable instead of writing the literal word staging directly.

Loading editor…
Exercise

Export an environment variable `EDITOR` set to `nano`, then — using that variable, not the literal word `nano` — create a file `nano.log` containing the text `ready`.

Quiz

Why is $HOME useful in a script instead of hard-coding a path like /home/user?

Checkpoint

You can export environment variables and use them to make commands and scripts configurable instead of hard-coded.