Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getopts checking for mutually exclusive arguments

Tags:

bash

getopts

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
like image 786
Chris Snow Avatar asked Feb 12 '14 07:02

Chris Snow


People also ask

What is the purpose of getopts command?

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.

What does colon mean in getopts?

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.

Which of these is a difference between getopt and getopts?

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.

What does getopts mean in Bash?

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.


1 Answers

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
like image 107
anubhava Avatar answered Sep 17 '22 21:09

anubhava