Environment Variables — Settings That Travel
Programs often need to know things about you, such as your home folder, your username, your preferred editor and where to look for commands. They don't ask each time. They read environment variables, small named values that the shell passes to every program it starts.
The rule
Set it, export it, and only children see it.
Set a variable with NAME=value, with no spaces around the =. Read it with a $ in front:
$ GARDEN_DIR=/home/asha/garden
$ echo $GARDEN_DIR
/home/asha/gardenAt this point it's only a shell variable, and the programs the shell starts can't see it. Export it to put it in the environment:
$ export GARDEN_DIR
$ export EDITOR=nano # set and export in one stepExported variables are copied into every child process the shell starts, such as a script, an editor or another shell. A child gets its own copy, so if a script changes a variable, the shell that started it keeps the old value.
A few you'll see everywhere:
| Variable | Holds |
|---|---|
HOME |
your home directory; ~ is a shortcut for it |
USER |
your username |
PATH |
where the shell looks for commands |
EDITOR |
the editor tools should open for you |
PWD |
the current directory |
SHELL |
your login shell |
Useful tools:
envorprintenvlists every exported variable.printenv HOMEshows just one.unset GARDEN_DIRremoves a variable.NAME=value commandsets a variable for that one command only:EDITOR=vim crontab -e.
Variables you set by typing disappear when the terminal closes. To keep one, put the export line in your shell's startup file, such as ~/.bashrc for Bash, and it will be set in every new shell.
The shortcut
When a program "can't see" a setting, ask two questions: was it exported, and was it set in this shell or a parent of it? A variable only travels down the family tree, from a parent to its children, and only if it was exported.
The symptom
Her script prints an empty line where the folder should be.
The other common trap is spaces: GARDEN_DIR = /home/asha/garden makes the shell try to run a command called GARDEN_DIR with two arguments.
Drills
Answer fast — trust the rule.
Which line correctly sets a variable in Bash?
Asha runs TOOL=shovel and then a script that prints $TOOL. The script prints nothing. Why?
A script runs export EDITOR=vim. After it finishes, what is EDITOR in the terminal that started it?
How do you run one command with LANG=C without changing LANG for the rest of the session?
Remember
- Set it, export it, and only children see it:
NAME=value, thenexport NAME. - If a program can't see a setting, check whether it was exported and whether it was set in this shell or a parent.
- No spaces around
=, and putexportlines in~/.bashrcto keep them.
