UNIX and Linux Shell Script Special Variables

The shell sets a few handy variables for us. Here are some of the more important ones

 

$?

The exit status (or return value) of the last command. This should be zero, unless the last command failed.

$0

The name of the command being executed. For example, if you had a script called fred which just contained this one line:

echo My name is $0

You could run it as follows to output the script name:

user@host sh fred
My name is fred

$0 does contain the full path, so be careful:

user@host sh /tmp/fred
My name is /tmp/fred

$#, $1, $2, $3 etc

$# returns the number of parameters passed to the command. $1, $2, $3 etc are these parameters

In this example we expand on our fred script to check if we pass parameters to the script and output the first and second ones if they exist. Note the use of the "and" operator (&&), explained on this page and the "greater than" test (-gt) explained here.

Here's the script, called fred


echo My name is $0
[ $# -gt 0 ] && echo The first parameter is $1
[ $# -gt 1 ] && echo The second parameter is $2

Here's how we run it:

user@host sh fred
My name is fred
user@host sh fred one two
My name is fred
The first parameter is one
The second parameter is two

$@

$@ returns the all the parameters passed to the command. This is useful if you want to use a shell script as a wrapper for another program.

To show how this works, here's a one line script called allParams:


echo you gave me \"$@\"

Here's how we run it:

user@host sh allParams this is a test
you gave me "this is a test"

$$

$$ returns the process number of the shell. These are handy in the creation of temporary filenames. As in this example:

echo "my temp info" >/tmp/stuff.$$.tmp

Assuming the PID of the current shell is 1234, the filename will be "/tmp/stuff.1234.tmp"

$!

This returns the process number of the last process to be run in the background. For example, here we run a sleep command and put it into the background, then return it's PID.

user@host sleep 100&
[1] 31174
user@host echo $!
31174