I'm writing a bash script, parsing options with getopts like this:

    #!/bin/bash

    while getopts ab: ; do
        case $opt in
          a) AOPT=1
             ;;
          b) BOPT=$OPTARG
             ;;
        esac
    done

I'd like to have the "-b" option OPTIONALLY take an argument, but as it is, getopts complains if no argument is passed. How can I accomplish this?

Thanks!

link|improve this question

1  
it would be courteous of you to go back and "accept" answers to your previous questions where appropriate. Looks like you've accepted none of them so far. It's just a way to give back to the SF community. Thanks! – ErikA May 6 '11 at 4:35
Oops, sorry - I hadn't quite gotten the hang of the system yet. – Frank Brenner May 11 '11 at 7:58
No problem, Frank. – ErikA May 11 '11 at 14:18
feedback

1 Answer

up vote 3 down vote accepted

You can run getopts in silent mode by including a colon as the first character of the optstring. This can be used to suppress the error message.

From the getopts manpage:

If the first character of optstring is a colon, the  shell  variable specified  
by name shall be set to the colon character and the shell variable OPTARG shall 
be set to the option character found.

Thus something like the following might work for you:

#!/bin/bash

AOPT="unassigned"
BOPT="unassigned"

while getopts :ab: opt ; do
  case $opt in
    a) AOPT=1
       ;;
    b) BOPT=$OPTARG
       ;;
    :) BOPT=
       ;;
  esac
done

echo "AOPT = $AOPT"
echo "BOPT = $BOPT"

Some examples:

rlduffy@hickory:~/test/getopts$ ./testgetopts -a -b Hello
AOPT = 1
BOPT = Hello
rlduffy@hickory:~/test/getopts$ ./testgetopts -b goodbye
AOPT = unassigned
BOPT = goodbye
rlduffy@hickory:~/test/getopts$ ./testgetopts -a -b
AOPT = 1
BOPT = 
link|improve this answer
Awesome, thanks – Frank Brenner May 11 '11 at 7:58
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.