Having getopts to show help if no options provided

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).


Many thanks to Etan Reisner, I ended up using your suggestion:

if [ $# -eq 0 ];
then
    help_message
    exit 0
else
...... remainder of script

This works exactly the way I supposed. Thanks.

Tags:

Bash

Getopts