user1190411
user1190411

Reputation: 341

Linux bash, getting getopt default parameters

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 :)

Upvotes: 2

Views: 842

Answers (1)

glenn jackman
glenn jackman

Reputation: 246807

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' --

Upvotes: 4

Related Questions