Skip to content

Linux Foundations / Find your way around Linux ยท Step 35 of 63

Lesson: env (Environment)Switch
โ† Linux Foundations

Shell and files

env (Environment)

Learn what environment variables are, how to read and set them, and how PATH works.

Your shell keeps named values that describe your session, such as your home directory and language. Those that are passed on to the programs you start are called environment variables.

Look at the environment

env with no arguments prints every environment variable. printenv can also show just one.

$ env
HOME=/home/maya
SHELL=/bin/bash
LANG=en_GB.UTF-8
...
$ printenv HOME
/home/maya

In a command line, put $ before a name and the shell substitutes the value.

$ echo "My files are in $HOME"
My files are in /home/maya

Single quotes stop that substitution, so echo '$HOME' prints the five characters $HOME.

Shell variables and export

Setting a variable with no spaces around = creates a shell variable. Child processes do not receive it until you export it.

$ COLOR=blue
$ sh -c 'echo "[$COLOR]"'
[]
$ export COLOR
$ sh -c 'echo "[$COLOR]"'
[blue]

You can combine both steps as export COLOR=blue. Remove a variable with unset COLOR. Changes made in a child process never travel back to the parent.

Set a variable for one command

Write the assignment before the command. It applies to that command only.

$ TZ=UTC date

The env program can do this too: env TZ=UTC date. It also has -u NAME to leave a variable out (GNU and BSD versions) and -i to start with an empty environment.

PATH

PATH is a list of directories, separated by colons, that the shell searches when you type a command name.

$ echo $PATH
/usr/local/bin:/usr/bin:/bin
$ command -v sort
/usr/bin/sort

To add a directory, keep the old value:

$ export PATH="$PATH:$HOME/bin"

Writing export PATH=$HOME/bin would replace the list, and commands like ls would no longer be found by name.

Making changes last

An export lasts only for the current shell. To keep it, add the line to a startup file. For Bash, interactive non-login shells read ~/.bashrc, while login shells read ~/.profile or ~/.bash_profile. Which one applies differs between distributions, and other shells use other files.

See the shell navigation lab for hands-on work.

Try it

  1. Run printenv HOME SHELL.
  2. Set PET=cat, then run printenv PET. Nothing appears.
  3. Run export PET and try again.
  4. Run env -i /usr/bin/env and compare it with plain env.

Check your understanding

env (Environment)

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.