next up previous contents
Next: Input/Output Up: Shell Programming Previous: Strings   Contents

Passing in Arguments

The special variables $1, $2, $3... are used to hold the arguments that are passed to the script. For example if the file my_commands contains:-

#!/bin/sh
echo "Input args are $1 $2 $3 etc."
exit 0

Then the command:-

./my_commands abc 123 def
produces:-
Input args are abc 123 def etc.

The variable $# hold the number of arguments. The variable $0 holds the name of the script file itself. When sourcing a file, $0 holds the shell file name.

Sometimes life is not so simple and you have to deal with a variable number of arguments, for example:-

./my_commands *.cxx *.dat

and then command shift is useful as it removes the first argument ($1) and shifts all the others down by one ( so $2 becomes $1, $3 becomes $2 etc.)

For example if the file my_commands contains:-

#!/bin/sh
echo "Input args are:-"
echo "$1"
shift
echo "$1"
shift
echo "$1"
exit 0

Then the command:-

./my_commands abc 123 def
produces:-
Input args are:-
abc
123
def


next up previous contents
Next: Input/Output Up: Shell Programming Previous: Strings   Contents
P.D. Gronbech (IT Staff) 2015-10-02