I have a simple script (below) that has mutually exclusive arguments.
The arguments for the script should be ./scriptname.sh -m|-d [-n]
, however, a user can run the script with ./scriptname.sh -m -d
which is wrong.
Question: how can I enforce that only one of the mutually exclusive arguments have been provided by the user?
#!/bin/sh
usage() {
cat <<EOF
Usage: $0 -m|-d [-n]
where:
-m create minimal box
-d create desktop box
-n perform headless build
EOF
exit 0
}
headless=
buildtype=
while getopts 'mdnh' flag; do
case "$flag" in
m) buildtype='minimal' ;;
d) buildtype='desktop' ;;
n) headless=1 ;;
h) usage ;;
\?) usage ;;
*) usage ;;
esac
done
[ -n "$buildtype" ] && usage
The getopts command is a Korn/POSIX Shell built-in command that retrieves options and option-arguments from a list of parameters. An option begins with a + (plus sign) or a - (minus sign) followed by a character. An option that does not begin with either a + or a - ends the OptionString.
An option character in this string can be followed by a colon (' : ') to indicate that it takes a required argument. If an option character is followed by two colons (' :: '), its argument is optional; this is a GNU extension. getopt has three ways to deal with options that follow non-options argv elements.
getopt vs getopts The main differences between getopts and getopt are as follows: getopt does not handle empty flag arguments well; getopts does. getopts is included in the Bourne shell and Bash; getopt needs to be installed separately.
Updated: 02/01/2021 by Computer Hope. On Unix-like operating systems, getopts is a builtin command of the Bash shell. It parses command options and arguments, such as those passed to a shell script.
I can think of 2 ways:
Accept an option like -t <argument>
Where argument can be desktop
or minimal
So your script will be called as:
./scriptname.sh -t desktop -n
OR
./scriptname.sh -t minimal -n
Another alternative is to enforce validation inside your script as this:
headless=
buildtype=
while getopts 'mdnh' flag; do
case "$flag" in
m) [ -n "$buildtype" ] && usage || buildtype='minimal' ;;
d) [ -n "$buildtype" ] && usage || buildtype='desktop' ;;
n) headless=1 ;;
h) usage ;;
\?) usage ;;
*) usage ;;
esac
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With