kami
kami

Reputation: 187

apache.commons.cli and "long" command-line parameters in Java

Is it possible to use 'long' parameters for command-line options with apache.commons.cli.CommandLineParser in java? 'Long' I mean not a single word, but a sentence in block-quotes ('"'). Java application is being started from bash-script file.

Script file:

#!/bin/bash
java -cp <classpath> MyClass $@

Call (which returns only "long" for '-p' argument and "another" for '-r' argument):

./script.sh -p "long parameter" -r "another long parameter"

Now I can only do something like this to get "long parameter" string:

./script.sh -p "long" -p "parameter"

Of course I can add '-p' programmatically as many times as needed, but this prevents me from using '-' sign in parameter values, as I need to track other command-line switches. Besides this seems to be far not correct approach.

CommandLine options are created like this:

org.apache.commons.cli.Options options = new Options();
options.addOption(Option.builder("p").longOpt("param").hasArg().desc("parameter description").build());

And then parsed like this:

CommandLineParser parser = new DefaultParser();
CommandLine         line = parser.parse( options, args );
if (line.hasOption('p')) params = line.getOptionValues("param");

Upvotes: 2

Views: 1376

Answers (1)

kami
kami

Reputation: 187

Finally it's got clear (thanks to Jim Garrison) that the problem is caused by calling java class from bash-script (passing all the arguments with $@). Wrapping $@ into double quotes in script solved the problem. Like this:

#!/bin/bash
java -cp <path> MyClass "$@"

instead of incorrect

#!/bin/bash
java -cp <path> MyClass $@

Upvotes: 2

Related Questions