1

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!

Frank Brenner
  • 175
  • 5
  • 11
  • 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! – EEAA May 06 '11 at 04:35
  • Oops, sorry - I hadn't quite gotten the hang of the system yet. – Frank Brenner May 11 '11 at 07:58
  • No problem, Frank. – EEAA May 11 '11 at 14:18

1 Answers1

4

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 = 
rlduffy
  • 231
  • 1
  • 4