Malvin
Malvin

Reputation: 859

Shell: Is it possible to parse optional parameters after non-optional ones?

Lately I tried to to pass arguments in a shell script like this:

$./myscript.sh <sourcefile> <destinationfile> -o

The script should read in a sourcefile and a destinationfile - both should be mandatory - and then check additional optional parameters in the end. However when trying to parse the option -o with getopts - it never finds it. It's always "false" or "0". It only recognizes the option -owhen it's passed before the other parameters!

$./myscript.sh -o <sourcefile> <destinationfile>

Is this mandatory that it only works this way? When I'm googling for rules, conventions or practise in scripts I never find these essential informations and only find it out through trial and error wasting a lot of time... Also I wonder how then a copy command process works, as it also mixes optional with non optional parameters

Upvotes: 3

Views: 285

Answers (1)

rici
rici

Reputation: 241721

Traditionally in unix, optional parameters have come first, at least for most shell utilities, and that is the Posix recommendation for writing shell utilities. The bash builtin getopts is designed for this use case as well; unless you yourself reorder the command line parameters, getopts will only work with option parameters coming first.

However, most gnu utilities use the gnu getopt or getopt_long C APIs, both of which by default allow optional parameters to come anywhere in the command line. And even with Posix shell utilities, there are some exceptions to the standard.

In short:

  • you should always be safe putting optional parameters first, but in some cases you can put them at the end

  • utilies written using the bash getopts built-in practically always require optional parameters to come first

  • most Gnu utilities allow intermingled optional and positional parameters

Upvotes: 2

Related Questions