Skip to the workspace
Pebellslearn by building
Shell and Other Basics  ›  Lesson

Environment Variables — Settings That Travel

Environment Variables 12 minA variable set with NAME=value stays in the shell until it is exported, after which child processes receive a copy.

linux / Environment Variables — Settings That Travel

Explore each scene at your own pace.

01 · The rule

The rule

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/garden

At 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 step

Exported 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:

  • env or printenv lists every exported variable. printenv HOME shows just one.
  • unset GARDEN_DIR removes a variable.
  • NAME=value command sets 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.