getopts
is an option parsing tool; it doesn't handle logic and semantics (the meaning of options, required options or forbidden combos, etc). Those go in the code around getopts
(as @Jens suggested in a comment). Here's a simple example:
# Default values:
flag1="false" # Note: "false" is just a text string, this is a cheat.
flag2="false" # See note at end.
year=2001
number=42 # because 42 is the correct default number
# Parse the supplied options
while getopts "y:n:12" OPT; do
case "$OPT" in
y)
year=${OPTARG}
;;
n)
number=${OPTARG}
;;
1)
flag1="true"
;;
2)
flag2="true"
;;
*)
echo "Usage: $0 [-y year] [-n number] [-1|-2]" >&2
exit 1
;;
esac
done
shift $((OPTIND-1))
# Enforce rules about option combos
if $flag1 && $flag2; then
echo "$0: The options -1 and -2 cannot be specified together." >&2
exit 1
fi
This is really just a bog-standard invocation of getopts
to parse options, folowed by an if
statement to enforce the rule that -1
and -2
can't be used together. That's all there is to it.
Note that I'm treating flag1
and flag2
as boolean variables, but there's really no such thing in shell syntax; they're actually just strings. That happen to correspond to commands. That happen to work in a semi-intuitive way in if
statements. But it's a cheat, so don't mistake them for real boolean variables. See here for some more info.