Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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!

share|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! –  EEAA 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. –  EEAA May 11 '11 at 14:18
add comment

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 = 
share|improve this answer
    
Awesome, thanks –  Frank Brenner May 11 '11 at 7:58
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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