Having getopts to show help if no options provided

Omar picture Omar · Oct 27, 2014 · Viewed 11.4k times · Source

I parsed some similar questions posted here but they aren't suitable for me.

I've got this wonderful bash script which does some cool functions, here is the relevant section of the code:

while getopts ":hhelpf:d:c:" ARGS;
do
    case $ARGS in
        h|help )
            help_message >&2
            exit 1
            ;;
        f )
            F_FLAG=1
            LISTEXPORT=$OPTARG
            ;;
        d )
            D_FLAG=1
            OUTPUT=$OPTARG
            ;;
        c )
            CLUSTER=$OPTARG
            ;;
        \? )
            echo ""
            echo "Unimplemented option: -$OPTARG" >&2
            echo ""
            exit 1
            ;;
        : )
            echo ""
            echo "Option -$OPTARG needs an argument." >&2
            echo ""
            exit 1
            ;;
        * )
            help_message >&2
            exit 1
            ;;
    esac
done

Now, all my options works well, if triggered. What I want is getopts to spit out the help_message function when no option is triggered, say the script is launched just ./scriptname.sh without arguments.

I saw some ways posted here, implementing IF cycle and functions but, since I'm just starting with bash and I already have some IF cycles on this script, I would like to know if there is an easier (and pretty) way to to this.

Answer

Etan Reisner picture Etan Reisner · Oct 27, 2014

If you just want to detect the script being called with no options then just check the value of $# in your script and exit with a message when it is zero.

If you want to catch the case where no option arguments are passed (but non-option arguments) are still passed then you should be able to check the value of OPTIND after the getopts loop and exit when it is 1 (indicating that the first argument is a non-option argument).