LESSON · 1 OF 6

Environment variables

Environment variables

Every shell session carries a set of environment variables, name-value pairs the shell (and any program it runs) can read. They carry configuration that changes per user, per machine, or per session, without touching any source code.

Seeing them

bash
env                # every exported variable in this session
printenv           # same, slightly different format
echo $HOME         # print one specific variable
echo $USER
echo $PATH

$VAR is how the shell expands a variable's value.

Ones you'll meet daily

  • HOME - your home folder path
  • USER - your username
  • PWD - the folder you're standing in
  • SHELL - which shell is running
  • PATH - where the shell looks for command binaries (its own topic in the next node)
  • LANG - locale, controls sorting and message language

Setting a variable

bash
name=alice           # sets a shell variable, NOT exported
echo $name           # alice

That variable exists in your current shell, but any command the shell starts doesn't see it. To make a variable available to child processes, export it:

bash
export name=alice

Now name is in the environment. Any program you run from this shell sees it.

The inline form

You'll often see this pattern:

bash
LOG_LEVEL=debug ./deploy.sh

Sets LOG_LEVEL=debug for the duration of that single command. The variable is exported to deploy.sh, then discarded when the command finishes. Handy for scripts that read config from the environment.

Removing a variable

bash
unset name

Gone from the current session.

Spin up a fresh environment and practice live.
linux-devops-basic · fresh machine · ready in under a minute