0

I cannot seem to figure out why my simple bash script is parsing not declared flags. Here is how it looks:

#!/bin/bash 

while getopts "hi" OPTIONS
do

        case $OPTIONS in
                   h)     
                        echo "usage:"
                        echo "./scriptname.sh [options]"
                        echo " "
                        echo "options:"
                        echo "-i              install it"
                        echo "-h              show help menu"
                        exit 0
                        ;;

                   i)     
                        echo "this is function -i"
                        exit 0
                        ;;
                \?)
                        echo "illegal option"
                        exit
                        ;;
        esac
done

What happens is that it works just fine when passing -h and -i, however if typing -isomething and -hsomethingelse it will still return the options declared for h and i, as it seems to be ignoring anything else typed after -i and -h.

Essentially script should only parse -i and -h and return "illegal option" for anything else, even if option starts with either -i or -h, example -hospital.

I tried separating the two letters in while getopts with :, however that way either -i or -h will work, depending how : are positioned.

Example

while getopts "h:i:" OPTIONS
do

Thanks

mailman
  • 195
  • 1
  • 1
  • 8
  • getopts interprets only the first character as the option and the rest as an argument. See [here](https://stackoverflow.com/a/3975207/7443472) for example. Using colons means that you expect arguments for the preceding option, which is probably why your second example isn't working as intended. See [here](https://stackoverflow.com/a/18414091/7443472) for more information. You could probably check whether "$OPTARG" contains something manually in each of your options as a quick workaround. – Secespitus Jul 10 '19 at 09:35
  • Does it mean I need a getopts for each and every flag? Thanks – mailman Jul 10 '19 at 09:56
  • No, I meant in each of your case-statements in the first example [the "h)" and "i)" cases] you could do something like (pseudocode) "IF $OPTARG is not empty THEN throw error 'Illegal Option' ELSE print usage". Sorry, but I currently can't write up a proper answer, so this is only a pointer to something you could try as a workaround. – Secespitus Jul 10 '19 at 10:02
  • That is fine, thanks for the explanation. I will try to come up with something later today. – mailman Jul 10 '19 at 10:06

0 Answers0