8. Environment variables and paths¶
The command line is not just manipulating files: the shell has an internal state determined by the values of environment variables. They can influence the way that programs run under the shell.
To see what variables are set in your environment, run:
$ env
or:
$ env | less -S
if you want to scroll around the output a bit.
You’ll notice that environment variables are usually given ALL-CAPITAL names. This is just a convention: if you define your own variables you can use any convention you like, although breaking conventions for no good reason is most likely to cause trouble later.
One of the most important environment variables is
PATH
. This is a list of file-system absolute paths
(i.e. paths that start with the root location /
), separated by
colons.
You can have a look at your PATH variable either by scanning or grep-ing the output of env. Or, more instructively, by using variable expansion:
$ echo $PATH
Try printing out the values of the shell variables PWD
,
HOME
, USER
and SHELL
this way.
Variable expansion is very useful: the $ sign prefixing the variable name means replace this variable name with its associated value. You can also use variable expansions inside double-quoted text strings quite neatly:
$ echo "My name is $USER"
So what is PATH
used for? It is the list of directories that
the shell searches for the commands you type. If you have two
executable command files in separate directories listed in
PATH
, the one in the first listed directory will be run when
you call that command name.
How would you add directories to your existing path?
To find out where e.g. the ls command is located, use:
$ which ls
Where is that directory in your PATH
? Try with some other
commands you’ve been using.
Note
Why shouldn’t you usually put . (the current directory)
into your PATH
, and definitely not early on?
What happens if two consecutive colons (::) are in your
PATH
?
To assign a value to a variable, we use an = sign:
$ MYFOO=bar
$ echo $MYFOO
bar
Note that the lack of spaces around the = sign is important — this is a bash syntax quirk that often catches people out. Also note that the dollar sign is not used when assigning to the variable name.
You can of course reference variable values in assignments, too:
$ MYBAR=foo${MYFOO}baz
$ echo $MYBAR
foobarbaz
What did the braces in ${MYFOO}
do? What would happen if you
didn’t use them?
The export command can be put in front of a variable assignment to make sure the variable is passed on to child processes. Here’s a demo:
$ foo=bar
$ bash # open a new bash shell as a child of the previous one
$ echo $foo # returns empty
Here foo
is not a variable in the child process.
Now press Ctrl-d to exit the child shell and try
again with export:
$ export foo=bar
$ bash
$ echo $foo
bar
Does it work now?