2

I'm trying to write a moderately difficult bash program, but somehow I cannot parse command line parameters and set default parameters with getopt.

Getopt is somehow ignoring optional parameters, setting them after the --, which denotes end of parameters.

Simple test, where l(list) is required:

getopt -s bash -o l: -l list: -- -l test

Produces:

-l 'test' --

If I were to define l(list) as optional, then output is:

getopt -s bash -o l:: -l list:: -- -l test

-l '' -- 'test'

I used this example as a base, but as of my testing, even this script does not work as intended(setting arga value to something produces always default value).

OS: Linux, getopt -V=getopt from util-linux 2.27

Any help appreciated :)

1
  • 1
    IIRC getopts will only work with short options, not long ones. The code in that tutorial is doing its own parsing to iterate through options. There are almost certainly a lot of questions/answers/examples on SO (and the rest of the web) about this. Commented Oct 15, 2015 at 14:13

1 Answer 1

4

Check the man page:

A simple short option is a '-' followed by a short option character. If the option has a required argument, it may be written directly after the option character or as the next parameter (i.e. separated by whitespace on the command line). If the option has an optional argument, it must be written directly after the option character if present.

So you want

$ getopt -s bash -o l:: -l list:: -- -ltest
 -l 'test' --

Similarly, for optional long args, you must provide the argument in a specific way:

required

$ getopt -s bash -o l: -l list: -- --list foo
 --list 'foo' --
$ getopt -s bash -o l: -l list: -- --list=foo
 --list 'foo' --

optional

$ getopt -s bash -o l:: -l list:: -- --list foo
 --list '' -- 'foo'
$ getopt -s bash -o l:: -l list:: -- --list=foo
 --list 'foo' --
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for pointing out the relevant part in manual. I read the manual, but seems I skimmed over it, was too long. getopt seems a little inconsistent in style between mandatory arguments and optional arguments. Seems I had Idée fixe, that all programs in linuxland supporting long parameters use program --param <arg|undefined>
Thanks for setting me straight. I didn't even notice the difference -- I don't do enough bash these days to remember the details without typing man foo constantly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.