Parse unknown options in Apache Commons CLI

30 views Asked by At

Is there a way to parse unknown options which are not present in the Options object in Apache Commons CLI. For example- My args are --greeting hello --unknownArgument foo.

The Options object has greeting as an option: options.addOption("greeting", true, "display greeting");

But unknownArgument is not an option.

Is there a way i can still accept it as an option and do further processing (send it to a downstream process)?

1

There are 1 answers

0
centic On

The parsed commandline has a method getArgList(), which returns all remaining unparsed arguments, so it sounds like a good match.

However commons-cli complains about an unrecognized option if you try to pass in your commandline.

The only way to make it work is to add a double-dash, this serves as indicator that the library should stop parsing for commandline options.

E.g. see the following code-snippet, without the "--" it fails to parse the arguments:

    Option optGreeting = Option.builder()
            .hasArg(true)
            .longOpt("greeting")
            .build();
    Options opts = new Options();
    opts.addOption(optGreeting);

    String[] args = new String[] { "--greeting", "hello", "--", "--unknownArgument", "foo" };

    CommandLineParser parser = new DefaultParser();
    final CommandLine cmdLine;
    try {
        cmdLine = parser.parse(opts, args);
    } catch (ParseException ex) {
        System.err.println("Syntax error: " + ex.getMessage());
        return;
    }
    if (cmdLine.hasOption(optGreeting)) {
        for (String path : cmdLine.getOptionValues(optGreeting))
            System.out.println("greeting: " + path);
    }
    for (Object file : cmdLine.getArgList()) {
        System.out.println("additional: " + file);
    }