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.