[Next] [Previous] [Up] [Top] [Contents]

CHAPTER 9 Shell Programming

9.4 Variables


There are a number of variables automatically set by the shell when it starts. These allow you to reference arguments on the command line.

These shell variables are:

Shell Variables
VariableUsageshcsh
$#number of arguments on the command linex 
$-options supplied to the shellx 
$?exit value of the last command executedx 
$$process number of the current processxx
$!process number of the last command done in backgroundx 
$nargument on the command line, where n is from 1 through 9, reading left to rightxx
$0the name of the current shell or programxx
$*all arguments on the command line ("$1 $2 ... $9")xx
$@all arguments on the command line, each separately quoted ("$1" "$2" ... "$9")x 
$argv[n]selects the nth word from the input list x
${argv[n]}same as above x
$#argvreport the number of words in the input list x

We can illustrate these with some simple scripts. First for the Bourne shell the script will be:

#!/bin/sh

echo "$#:" $#

echo '$#:' $#

echo '$-:' $-

echo '$?:' $?

echo '$$:' $$

echo '$!:' $!

echo '$3:' $3

echo '$0:' $0

echo '$*:' $*

echo '$@:' $@

When executed with some arguments it displays the values for the shell variables, e.g.:

$ ./variables.sh one two three four five

5: 5

$#: 5

$-:

$?: 0

$$: 12417

$!:

$3: three

$0: ./variables.sh

$*: one two three four five

$@: one two three four five

As you can see, we needed to use single quotes to prevent the shell from assigning special meaning to $. The double quotes, as in the first echo statement, allowed substitution to take place.

Similarly, for the C shell variables we illustrate variable substitution with the script:

#!/bin/csh -f

echo '$$:' $$

echo '$3:' $3

echo '$0:' $0

echo '$*:' $*

echo '$argv[2]:' $argv[2]

echo '${argv[4]}:' ${argv[4]}

echo '$#argv:' $#argv

which when executed with some arguments displays the following:

% ./variables.csh one two three four five

$$: 12419

$3: three

$0: ./variables.csh

$*: one two three four five

$argv[2]: two

${argv[4]}: four

$#argv: 5


Introduction to Unix - 14 AUG 1996
[Next] [Previous] [Up] [Top] [Contents]