Bash – optional argument required but not passed for use in getopts

How do I flag an error in a bash script which requires an argument
for getopt, but the user didn’t pass it? e.g. the script below
requires an argument for option “t”:

#!/bin/bash
while getopts "ht:" OPTION
do
    case $OPTION in
        h)
            echo "Hi"
            ;;
        t)
            echo You entered $OPTARG
            ;;
    esac
done

I want to catch the below error and print something else and
exit. Currently, it goes on to evaluate more arguments without
exiting.

$ ./x.sh -h -t aa     # (this is fine)
Hi
You entered aa

$ ./x.sh -h -t       # (this is not handled)
Hi
No arg for -t option      # (this error is being printed by bash)


Source: shell

Leave a Reply