UNIX and Linux Shell Script Variables

Shell variables are a vital part to shell programming. You can assign a value to variables and print it out like this example:

user@host user=fred
user@host echo $user
fred

Note that there must be no spaces on either side of the "=". We can also assign the value of variables to other variables:

user@host user2=$user
user@host echo $user2
fred

A variable can be set to null like this:

user@host user=

Warnings about Wildcards in Variables

Here's an oddity about assigning variables that shows just how file system orientated the command shell is:

user@host files=/etc/ho*
user@host echo $files
/etc/host.conf /etc/hostname /etc/hosts /etc/hosts.allow /etc/hosts.deny
user@host echo "$files"
/etc/ho*

Looking at the first output, you might think that assigning "/etc/ho*" to a variable has expanded the answer to a directory listing of all files in /etc/ beginning with "ho". The second printout show that the variable is not set to a directory listing, so it's actually the echo command which is doing the file expansion. All we can learn from this is to be careful when playing with variables - if you're not sure what they are, put quotes around them!

Environment Variables

You can see what environment variables are set by typing "env". Environment variables are used for all sorts of wonderful things. For example "PATH" is used to tell the shell where to find executable programs.

In this example we set our PATH variable to NULL to show that the shell cannot find the "uname" program without it (unless we specify the full path). Setting PATH to something that includes the path of our command helps the shell to locate "uname" again.

user@host PATH=
user@host uname
sh: uname: not found
user@host /bin/uname
Linux
user@host PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
user@host uname
Linux

Exporting Variables

If you want to make a variable accessible to shells run from within your shell, you need to use the "export" command. An example is the best way of demonstrating this. So, in this example we set the variable named "animal" to the value "goose". We can use this variable locally, but if we try and execute this command from another shell (using "sh -c command_string" to invoke a new shell and run command_string) we see that the new shell cannot see the variable. Exporting the variable makes it available to the new shell.

user@host animal=goose
user@host echo $animal
goose
user@host sh -c 'echo $animal'

user@host export animal
user@host sh -c 'echo $animal'
goose

The shell also sets some special variables, which are explained here.