Skip to content

Variables - Part II

Linux offers a set of pre-defined variables. These pre-defined variables contain useful information.

The first set of variables are $0, $1, ..., $9, and $#.

The variable $0 is the name of the program as it was called. For example, if you run example.sh which uses the variable $0, it will return example.sh. $1, ..., $9 are the first 9 additional parameters the script was called with. The total number of parameters that the script is called with is stored in $#.

To access all parameters at once, we can use $@ and $*. $@ is a special variable takes the entire list of parameters and separates them into a list of parameters. Thus, the variable $@ is all parameters $1, ..., $any_number.  The variables $* is similar but does not preserve any whitespace or quoting, so "File with spaces" becomes "File" "with" "spaces". This is similar to the echo command.

Let's do a hands on example.

var4.sh
1
2
3
4
5
6
#!/bin/sh
echo "Number of parameters from input: $# parameters"
echo "My name is $0"
echo "My first parameter is $1"
echo "My second parameter is $2"
echo "All parameters are $@"

Here is a sample run for the above script.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$ sh ./var4.sh
Number of parameters from input: 0 parameters
My name is ./var4.sh
My first parameter is
My second parameter is
All parameters are

$ sh ./var4.sh My lazy fox
Number of parameters from input: 3 parameters
My name is ./var4.sh
My first parameter is My
My second parameter is lazy
All parameters are My lazy fox

$# and $1, ..., $9 are set by the shell. We can take more than 9 parameters by using the shift command. Look at the next example.

test.sh
1
2
3
4
5
6
#!/bin/sh
while [ "$#" -gt "0" ]
do
  echo "\$1 is $1"
  shift
done    

The backslash character \ is used to "escape" $ so that it is not interpreted by the shell. This script uses shift to move all parameters down one slot (removing $1) until $# is down to zero.

Here is a sample run for the above script.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$ sh ./test.sh The quick brown fox jumps over the lazy dog.
$1 is The
$1 is quick
$1 is brown
$1 is fox
$1 is jumps
$1 is over
$1 is the
$1 is lazy
$1 is dog.

We can write a script using $* to get the same result.

1
2
3
4
5
6
#!/bin/sh

for TOKEN in $*
do
    echo \$1 is $TOKEN
done

In the previous scripts, while, for, and do ... done are loop commands which will be covered later.

The $? variable represents the exit status of the previous command. Exit status is a numerical value returned by every command upon its completion. Most commands return 0 if they were successful, and 1 if they were unsuccessful.

test.sh
1
2
3
4
5
6
7
#!/bin/sh

for TOKEN in $*
do
    echo \$1 is $TOKEN
done
echo $?

Here is the result of the sample run.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$ sh ./test.sh The quick brown fox jumps over the lazy dog.
$1 is The
$1 is quick
$1 is brown
$1 is fox
$1 is jumps
$1 is over
$1 is the
$1 is lazy
$1 is dog.
0

See also