madbitloman
madbitloman

Reputation: 826

How to exit getopt if two specific arguments are passed?

What I am trying to do is that if two specific arguments are passed at once then script would exit and HELP function is executed.

while getopts ":H:D:S:h:" arg; do
case "${arg}" in
H) HOUR=${OPTARG};;
D) DAY=${OPTARG};;
h) HELP;;
\?) #unrecognized option - show help
    HELP;;

So that script if both H and D are presented I would like to terminate the script running and ask user to type it again.

Obviously I could use something like:

if [[ -z "$HOUR"  || -z "$DAY"  ]]
  then
    HELP

But was wondering if there are better options to do something like that. Cheers!

Upvotes: 0

Views: 649

Answers (1)

chepner
chepner

Reputation: 531075

getopts doesn't provide any explicit support for mutually exclusive options. I would suggest catching it in the case statement:

case $arg of
    -H) if [[ -n $DAY ]]; then
          printf '-D already detected\n'
          exit 1
        else
          HOUR=$OPTARG
        fi
        ;;
    -D) if [[ -n $HOUR ]]; then
          printf '-H already detected\n'
          exit 1
        else
          DAY=$OPTARG
        fi
        ;;
    -h) HELP
        ;;
    *) HELP
       ;;
esac

Upvotes: 2

Related Questions