2

I spent quite a while researching the problem I encountered but none of the getopts tutorial say anything about the leading whitespace in OPTARG when using getopts.

In bash(on Ubuntu and OSX), executing below commands:

OPTIND=1 && getopts ":n:" opt "-n 1" && echo "OPTARG: '$OPTARG'"

and it echos:

OPTARG: ' 1'

However, if I execute this:

OPTIND=1 && getopts ":n:" opt "-n1" && echo "OPTARG: '$OPTARG'"

then I will get what I expect:

OPTARG: '1'

From what I read online:

Normally one or more blanks separate the value from the option letter; however, getopts also handles values that follow the letter immediately [Reference]

If the above quote is universally right for getopts, what do I do wrong that I get that leading whitespace in OPTARG?

1

You should just leave out the double quotes around "-n -1", as that is what preserves the space before the 1:

OPTIND=1 && getopts ":n:" opt -n 1 && echo "OPTARG: '$OPTARG'"

gives:

OPTARG: '1'
  • Thanks for the workaround!! I use getopts in my bash script and I will try if getopts ":n:" opt $@ will do the trick. Since it does not work if I don't explicitly pass $@ to the command like this getopts ":n:" opt – GJ. Nov 5 '14 at 2:52
  • It seems like getopts does not like the double quote around the option string. :) getopts ":n:" opt $@ works perfectly! – GJ. Nov 5 '14 at 3:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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