3

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
tso
  • 187
  • 4
  • 13
  • put it in question. Have no clue what to do, If $OPTARG is not there than this wont work too – tso Aug 03 '16 at 11:26
  • Use `while getopts h:c:s:d:I:p:r FLAG; do` – anubhava Aug 03 '16 at 11:29
  • Sorry, question not clear enough. Please put in question what exactly you wish to accomplish. – sjsam Aug 03 '16 at 11:33
  • I want to have a "-h" parameter in my script which, when I start the script via test.sh -h .. give me text output. My this -h parameter always need an argument when I start it .. test.sh -h xyz .. and I dont want to write that xyz. – tso Aug 03 '16 at 11:38

1 Answers1

8

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.

Fazlin
  • 2,285
  • 17
  • 29