Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Conditional" parsing of command-line arguments

Say I have an executable (running on mac, win, and linux)

 a.out [-a] [-b] [-r -i <file> -o <file> -t <double> -n <int> ]

where an argument in [ ] means that it is optional. However, if the last argument -r is set then -i,-o,-t, and -n have to be supplied, too.

There are lots of good C++-libraries out there to parse command-line arguments, e.g. gflags (http://code.google.com/p/gflags/), tclap (http://tclap.sourceforge.net/), simpleopt(http://code.jellycan.com/simpleopt/), boost.program_options (http://www.boost.org/doc/libs/1_52_0/doc/html/program_options.html), etc. But I wondered if there is one that lets me encode these conditional relationships between arguments directly, w/o manually coding error handling

if ( argR.isSet() && ( ! argI.isSet() || ! argO.isSet() || ... ) ) ...

and manually setting up the --help.

The library tclap allows to XOR arguments, e.g. either -a or -b is allowed but not both. So, in that terminology an AND for arguments would be nice.

Does anybody know a versatile, light-weight, and cross-platform library that can do that?

like image 782
nils Avatar asked Dec 19 '12 15:12

nils


People also ask

How do I parse bash script arguments?

We can use the getopts program/ command to parse the arguments passed to the script in the command line/ terminal by using loops and switch-case statements. Using getopts, we can assign the positional arguments/ parameters from the command line to the bash variables directly.

How do you access command line arguments from within a shell script?

The special character $# stores the total number of arguments. We also have $@ and $* as wildcard characters which are used to denote all the arguments. We use $$ to find the process ID of the current shell script, while $? can be used to print the exit code for our script.

How does bash handle command line arguments?

You can handle command-line arguments in a bash script in two ways. One is by using argument variables, and another is by using the getopts function.


1 Answers

You could two passes over the arguments; If -r is in the options you reset the parser and start over with the new mandatory options added.


You could also look into how the TCLAP XorHandler works, and create your own AndHandler.

like image 164
Some programmer dude Avatar answered Sep 19 '22 01:09

Some programmer dude