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/mayaIn a command line, put $ before a name and the shell substitutes the value.
$ echo "My files are in $HOME"
My files are in /home/mayaSingle 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 dateThe 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/sortTo 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
- Run
printenv HOME SHELL. - Set
PET=cat, then runprintenv PET. Nothing appears. - Run
export PETand try again. - Run
env -i /usr/bin/envand compare it with plainenv.
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.