Skip to content
Beginner LinuxLesson 6 of 27 2 min read

Environment Variables and PATH

Read and set variables with $VAR, export, and understand PATH.

On this page5 sections

Every running process, including your shell, keeps a table of environment variables - named strings like HOME, USER, or PATH that configure how programs behave.

Reading a variable

Put a $ in front of a variable's name and the shell substitutes its value before running the command:

bash
echo $HOME
echo "Logged in as $USER"

Wrap the name in ${ } when you need to be explicit about where the name ends, which matters right before more text:

bash
echo "${USER}_backup.tar"

Variables only expand when unquoted or inside double quotes. Single quotes turn expansion off - echo '$HOME' prints the literal text $HOME, not its value.

Setting a variable

bash
export STAGE=production   # define STAGE for this shell and any command it starts
echo $STAGE
env                        # list every variable currently exported

Any process you start after export inherits a copy of these variables - that is what "environment" means: it travels with the process, not just the current line.

PATH: how the shell finds commands

PATH is the most important environment variable of all. It is a colon-separated list of directories the shell searches, in order, whenever you type a bare command name like ls instead of a full path like /bin/ls. A typical value looks like:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

If a command reports "not found" even though the file exists, it is almost always because the directory holding it is missing from PATH.

Try it

Run these in the practice terminal (opens in a new tab). It opens in a new tab, so you keep your place here.
bash
export BUILD_ENV=staging
echo $BUILD_ENV
export BUILD_ENV=production
echo "now building for $BUILD_ENV"
env

Further reading

  • "Learning the bash Shell" by Cameron Newham (O'Reilly) - the definitive guide to shell variables, quoting rules, and the startup files (.bashrc, .bash_profile) that set them up for you automatically.
  • "The Linux Command Line" by William Shotts (No Starch Press) - the "Environment" chapter in Part II walks through exactly this material with more real-world examples.

Challenge

Create an environment variable named BUILD_ENV with the value staging, then print it back with echo. Do both in one line.

Want to experiment first? Try things in the practice terminal (opens in a new tab), then enter the command that solves the task here.

Quiz

Lock in the concepts. Score at least 80% to mark the lesson complete.

0 of 2 answered

Done with this one?

Skipped the challenge? You can mark the lesson complete by hand.

Your notes

Kept on this browser only.