Search code examples
bashgetopts

Having getopts to show help if no options provided


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.


Solution

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