The code below uses getopts
to parse options. When option a
is seen, it sets variable a
to have the value Yes
. Before doing that, however, it checks to see if a
already has a value. If it does, it prints an error.
#!/bin/sh
die () {
echo "ERROR: $*. Aborting." >&2
exit 1
}
a=
while getopts a arg ; do case $arg in
a)
[ "$a" ] && die "Option a already specified"
a=Yes
;;
:) die "${0##*/}: Must supply an argument to $OPTARG." ;;
\?) die "Invalid option. Abort" ;;
esac
done
shift $(($OPTIND - 1))
echo "Doing something useful now..."
The key part of the code is:
[ "$a" ] && die "Option a already specified"
The construct [ "$a" ]
tests the value of $a
. If it is non-empty, then the test returns true and this triggers the &&
operator to run the die
command. If it is empty, then [ "$a" ]
returns false and the die
command is not run.
die
is a function: it prints a message and exits with error code 1.