0

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.