CHAPTER 9 Shell Programming
These shell variables are:
Variable | Usage | sh | csh |
---|---|---|---|
$# | number of arguments on the command line | x | |
$- | options supplied to the shell | x | |
$? | exit value of the last command executed | x | |
$$ | process number of the current process | x | x |
$! | process number of the last command done in background | x | |
$n | argument on the command line, where n is from 1 through 9, reading left to right | x | x |
$0 | the name of the current shell or program | x | x |
$* | all arguments on the command line ("$1 $2 ... $9") | x | x |
$@ | 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 | |
$#argv | report 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