Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having getopts to show help if no options provided

Tags:

bash

getopts

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.

like image 520
Omar Avatar asked Oct 27 '14 16:10

Omar


2 Answers

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

like image 112
Etan Reisner Avatar answered Oct 07 '22 01:10

Etan Reisner


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.

like image 31
Omar Avatar answered Oct 06 '22 23:10

Omar