Search code examples
bashgetopts

Parsing options that take arguments in getopts


I have the following program foo, that can take one of three optional flags, f, g, or s:

usage()
{
    echo "Use this correctly"
}

while getopts "fgs" opt; do
    case $opt in
        f)
          echo f
          foo="$OPTARG"
          echo $foo
          ;;  
        g) 
          echo g 
          foo="g"
          ;;  
        s)  
          echo s
          foo="s"
          ;;  
    esac
done

if [ -z "$foo" ]
then
   usage
   exit
fi

echo $foo
exit

When I do foo -g or foo -s I get the expected outputs:

g
g

and

s
s

respectively. But when I do foo -f bar I expect

f
bar
bar

but get

f
Use this correctly

indicating that $foo is not being set properly in the -f case. What am I doing wrong?


Solution

  • You have to replace

    while getopts "fgs" opt; do
    

    with

    while getopts "f:gs" opt; do
    

    Options that take an argument must be followed by a colon. Only for these options, getopts sets the OPTARG variable.