How to resolve arguments without options in any getopt order?

I have a C program that expects a call with several parameters and one argument without an option (i.e., without the corresponding letter of the option) and uses getopt to parse these parameters. For example, it can be called using:

Example1: myProgram -a "aParam" -b "bParam" "xParam"

I am using SLES10 and the parameters worked in any order. For example, the non-option argument, "xParam" may be the first:

Example 2: myProgram "xParam" -a "aParam" -b "bParam"

However, when testing in SLES11, it seems that getopt stops processing as soon as it reaches a parameter without a parameter, so Example 2 above does not work.

I read the getopt man pages and saw that this could make a difference:

If the first optstring is “+” or the POSIXLY_CORRECT environment variable is set, option processing is terminated as soon as the nonoption argument is encountered.

I am not sure if SLES11 sets POSIXLY_CORRECT by default. What is the best way to get the old SLES10 getopt behavior in SLES11?

+4
source share
1 answer

It turns out that by default it was redirected to _posix_getopt (), which caused the behavior described above.

Possible solutions that I found at the end:

  • Use getopt_long () instead. It does not seem to have the posix equivalent.
  • Define _GNU_SOURCE, which stops the redirect.
  • Manually reorder the parameters, possibly using a shell script shell.
+1
source

Source: https://habr.com/ru/post/1444811/


All Articles