Text-only Table of Contents (frame/ no frame)
(11) Arguments Previous Top Next

Command Line (positional) arguments

To customize the behaviour of a script at run time, you can give it any number of arguments on the command line. More detail The shell expands wildcards and makes variable and command substitutions as normal, then parses the resulting words by whitespace (actually special variable $IFS), and places the resulting text strings into the positional variables as follows:
$0, $1, $2, ... $9
The first 9 arguments are made available directly as $1-$9. To access more than 9, use shift, or $*, $@. The variable $0 contains the name of the script itself.
${10}, ${11}, ...
Positional arguments greater than 9 are set by ksh and bash. Remember to use braces to refer to them.
discard $1 and renumber all the other variables. "shift N" will shift N arguments at once.
contains the number of arguments that were set (not including $0).
contains all of the arguments in a single string, with one space separating them.
similar to $*, but if used in quotes, it effectively quotes each argument and keeps them separate. If any argument contains whitespace, the distinction is important.
e.g. if the argument list is: a1 a2 "a3 which contains spaces" a4
then: $1=a1, $2=a2, $3=a3 which contains spaces, $4=a4
and: $*=a1 a2 a3 which contains spaces a4
and: "$@"="a1" "a2" "a3 which contains spaces" "a4"

Only using the form "$@" preserves quoted arguments. If the arguments are being passed from the script directly to some other program, it may make a big difference to the meaning.

Example: ex7 display, text

Setting new positional arguments

The set command, followed by a set of arguments, creates a new set of positional arguments. This is often used, assuming the original arguments are no longer needed, to parse a set of words (possibly using different field separators). Arguments may be reset any number of times.

Example: ex2 display, text

Example: pickrandom display, text
Selects a random file from a directory. Uses the ksh RANDOM feature.

Previous Top Next

arguments.src  last modified Sep 14, 2005 Introduction Table of Contents
(frame/no frame)
(single file)
© Dartmouth College