Shell – Execute default option when no options are specified in getopts

getoptsshell-script

I followed the tutorial here to learn how to use getopts. I'm able to execute all the options properly provided by the user. But now I want to execute a default option when none of the options are provided.

For e.g:

while getopts ":hr" opt; do
    case $opt in
        h )
            show_help;
            exit 1
            ;;
        r )
          echo "Default option executed"
          ;;
    esac
done

So, if the user provides with either -h or -r, the corresponding commands should be executed (which actually does) but when none of these options are provided -r should be executed by default. Is there a way to achieve this?

UPDATE

I tried cas's suggestion and included *) to my getopts function but nothing seems to be happening.

while getopts ":hr" opt; do
    case $opt in
        h )
            show_help;
            exit 1
            ;;
        r )
          echo "Default option executed"
          ;;

        \? )
          echo error "Invalid option: -$OPTARG" >&2
          exit 1
          ;;

        : )
          echo error "Option -$OPTARG requires an argument."
          exit 1
          ;;

        * )
          echo "Default option executed"
          ;;
    esac
done

Is there something wrong with this snippet?

Best Answer

Adding a default option to the case statement won't help because it won't be executed if getopts doesn't have options to parse. You can see how many options it processed with the OPTIND shell variable. From help getopts:

Each time it is invoked, getopts will place the next option in the
shell variable $name, initializing name if it does not exist, and
the index of the next argument to be processed into the shell
variable OPTIND.  OPTIND is initialized to 1 each time the shell or
a shell script is invoked.

So if OPTIND is 1, no options were processed. Add this after your while loop:

if (( $OPTIND == 1 )); then
   echo "Default option"
fi
Related Question