简体   繁体   中英

How to not allow the user to specify two options at once in getopts?

In getopts user can specify all the options that we introduce in the code. Give the following script.

while getopts d:s o
do  case "$o" in
    d)  seplist="$OPTARG";;
    s)  paste=hpaste;;
    [?])    print >&2 "Usage: $0 [-s] [-d seplist] file ..."
        exit 1;;
    esac
done

The user should not be allowed to specify both option -d and -s. ie.

When the user runs above script with both options -d and -s, he should receive an error cannot specify both -d and -s.

A naive implementation would be to maintain an $OPTION_COUNT :

OPTION_COUNT=0
while getopts d:s o
do  case "$o" in
    d)  seplist="$OPTARG"; (( OPTION_COUNT ++ );;
    s)  paste=hpaste; (( OPTION_COUNT ++ );;
    [?])    print >&2 "Usage: $0 [-s] [-d seplist] file ..."
        exit 1;;
    esac
done
if [ "$OPTION_COUNT" -gt 1 ]; then echo "too many options"; fi

You should check for particular options passed into the script. It will be much easier to maintain it.

#!/usr/bin/env bash
d_option=0
s_option=0
while getopts d:s o
do  case "$o" in
    d)
        seplist="$OPTARG"
        d_option=1
        ;;
    s)
        paste=hpaste
        s_option=1
        ;;
    [?])    print >&2 "Usage: $0 [-s] [-d seplist] file ..."
        exit 1;;
    esac
done
if [ "x$d_option" == "x1" ] && [ "x$s_option" == "x1" ]; then
    echo "both options specified."
    exit 1
fi

You should check for hints of other option.

while getopts d:s o
do  case "$o" in
    d)  if [ -z "$paste" ]; then
            seplist="$OPTARG"
        else
            print >&2 "Option -s is already specified"
            exit 1
        fi
        ;;
    s)  if [ -z "$seplist" ]; then
            paste=hpaste
        else
            print >&2 "Option -d is already specified"
            exit 1
        fi
        ;;
    [?])    print >&2 "Usage: $0 {-s | -d seplist} file ..."
        exit 1;;
    esac
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM