Search code examples
bashargumentsgetoptmanpagegetopts

Using getopts with no argument for help output


Hi I'm creating a bash script which uses getopts. Now I want to create an "-h" parameter to get the help. But every time I have to give one argument to the parameter.

Now

test.sh -h test

What I want

test.sh -h
help
help
help



while getopts :c:s:d:h:I:p:r FLAG; do
  case $FLAG in


        s)
                SOURCE=$OPTARG
                ;;
        d)
                DESTINATION=$OPTARG
                ;;
        I)
                ISSUE=$OPTARG
                ;;
        c)
                CUSTOMER=$OPTARG
                test -e /etc/squid3/conf.d/$CUSTOMER.conf
                customer_available=$?
                ;;
        p)
                PORT=$OPTARG
                ;;
        h)      HELP=$OPTARG
                echo help

Solution

  • A : after the option means the option requires an argument.

    OPTARG variable contains the argument that you pass to the option.

    If you do not want an argument, remove the : after h and also HELP=$OPTARG line.

    while getopts :c:s:d:hI:p:r FLAG; do
    ...
         h)      echo help
    ...
    done
    

    For further reference, check this link.