How to handle missing args in shell script

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"
  exit 2
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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)