0

The case statement in the bash script does not work. Below is the snippet of my shell script.

usage="Usage: \n servicer [ service argument ] {-h}\n"
invalid="\n not a valid option\n"
argument="\n Please use -h option for help\n"

while getopts ":h:s" option
        do
                case "${option}" in
                        s ) service=$OPTARG;;
                        h ) echo -e $usage
                           exit 0
                        ;;
                        * ) echo -e $invalid
                           exit 1
                        ;;
                esac
        done

So whenever i run my script with -h or -s option the flow goes to the last * option.

1 Answers1

1

The man getops page is not the easiest reading. Pretty sure you want getopts "hs:" . The colon represents a option-argument (parameter value) for the preceding option (the letter).

  • The h does not need a parameter, so there's no colon (:).

  • The s requires a parameter, hence s:. s without a parameter is also invalid as an argument is demanded by the colon.

  • Anything else is invalid.

I would also put your static strings (usage=, invalid=, argument=) in single quotes and double-quote the outputs.

usage='Usage: \n servicer [ service argument ] {-h}\n'
invalid='\n not a valid option\n'
argument='\n Please use -h option for help\n'
while getopts "hs:" option; do
    case "${option}" in
        s) service="$OPTARG"
            ;;
        h) echo -e "$usage"
            exit 0
            ;;
        *) echo -e "$invalid"
            exit 1
            ;;
    esac
done
Ian W
  • 239
  • 1
  • 2
  • 8