views:

25

answers:

2

What's the "right" way to handle missing arguments in a shell script? Is there a pre-canned way to check for this and then throw an exception? I'm an absolute beginner.

A: 

getopts is useful here: getopts

ennuikiller
A: 

Typical shell scripts begin by parsing the options and arguments passed on the command line. The number of arguments is stored in the # parameter, i.e., you get it with $#. For example, if your scripts requires exactly three arguments, you can do something like this:

if [ $# -lt 3 ]; then
  echo 1>&2 "$0: not enough arguments"
  exit 2
elif [ $# -gt 3 ]; then
  echo 1>&2 "$0: too many arguments"
fi
# The three arguments are available as "$1", "$2", "$3"

The built-in command exit terminates the script execution. The integer argument is the return value of the script: 0 to indicate success and a small positive integer to indicate failure (a common convention is that 1 means “not found” (think grep) and 2 means “unexpected error” (unrecognized option, invalid input file name, ...)).

If your script takes options (like -x), use getopts.

Gilles