Check if at least n arguments are present
$#
stores the number of arguments that were given when executing a shell script. Thus, it's possible to check if at least a given number of arguments are present.
The following fragment checks if at least 3 arguments were passed:
if [ $# -lt 3 ]; then
echo Error: At least 3 arguments are required.
exit 1
fi
# … rest of the shell script …
getopts
while getopts fx:h OPTION; do
case $OPTION in
f)
echo f was specfied
;;
x)
echo x was specified with value $OPTARG
;;
h)
echo $0 [-f] [-x value] [-h]
;;
esac
done
echo OPTIND=$OPTIND
$ ./script
OPTIND=1
$ ./script -h
./script [-f] [-x value] [-h]
OPTIND=2
$ ./script -x
./script: option requires an argument -- x
OPTIND=2
$ ./script -x foo
x was specified with value foo
OPTIND=3
$ ./script -xbar
x was specified with value bar
OPTIND=2
$ ./script -f -x baz
f was specfied
x was specified with value baz
OPTIND=4
The value of OPTIND
can be used to «shift away» the option arguments so that the required arguments can be processed:
shift $((OPTIND-1))