Skip to content
Advertisement

not allow multiple option in getopts of bash script

Having bash script as follows

#! /bin/bash

usage()
{
  echo -e "need help!"  
}

while getopts ":a:b:h" OPTION
do
     case $OPTION in
     a)
        printf "a option with value %sn" $OPTARG
        ;;
     b)
        printf "b option with value %sn" $OPTARG
        ;;
     h)
        usage
        ;;
     ?)
        echo -e "No option selected"
       ;;
    esac
done

exit 0

Above script run fine with different option but i wanted to extend it to not allow to pass multiple option at same time like as following argument

$ ./test.bash -a 1 -b 2
a option with value 1
b option with value 2

should be not valid means some way it give me error like wrong syntax i achieved it by as follows but it seems to long it is as follow

#! /bin/bash
usage()
{
  echo -e "need help!"  
}

let "a_count=0"
let "b_count=0"
MY_ARG=""
while getopts ":a:b:h" OPTION
do
     case $OPTION in
     a)
        let a_count=1
        MY_ARG=$OPTARG
        ;;
     b)
        let b_count=1
        MY_ARG=$OPTARG
        ;;
     h)
        usage
        ;;
     ?)
        echo -e "No option selected"
       ;;
    esac
done

[[ $a_count -eq 1 ]] && [[ $b_count -eq 1 ]] && echo "wrong command sytax" && exit 0

[[ $a_count -eq 1 ]] &&  printf "a option with value %sn" $MY_ARG

[[ $b_count -eq 1 ]] &&  printf "b option with value %sn" $MY_ARG

exit 0

run like

$ ./test.bash -a 1 -b 2
wrong command sytax

But i want to finish validation in while..loop of getopts. Also this validation not works for following command

./test.bash -a -b 
a option with value -b

any one have batter idea how to use getopts for this type validation?

Advertisement

Answer

you’ve almost got it. The : after the a and after the b say that they take an argument, so your example with -a -b is actually valid, saying “There is option a with value -b”.

If you really just want “-a or -b and then an argument”, you probably don’t need getopts at all, but should do:

[ "$1" == "-a" ] && printf "a option with value %sn" $2
[ "$1" == "-b" ] && printf "b option with value %sn" $2
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement