Search code examples
javabashpicocli

Bash strips quotes passed to java command line application


I have a java command line application written using Picocli, and I am trying to pass to it a string parameter, but every time I try the bash strips the quotes and I end with three parameters.

javaCLI install "Extras lib v0.1.4.cpkg"

This is the output I receive in bash

positional parameter at index 0..* (package_file) should be specified only once
Usage: javaCLI install package_file

I tried using escape single (\') and double quotes (\"), escape spaces (\ ), even both single and double quotes (with and without ) but none of them work. The easy solution is to rename the package to extras_lib_v0.1.4.cpkg but I will have the same problem with other methods.


Solution

  • My guess is that javaCLI is a wrapper script that calls java and that the quotes are stripped by this wrapper script.

    The error message "positional parameter at index 0..* (package_file) should be specified only once" tells me that the install subcommand has a single @Parameters-annotated String field named package_file, so it expects only a single positional parameter, but was invoked with multiple parameters.

    You can confirm that the java application incorrectly received 4 arguments instead of the desired 2 by setting system property -Dpicocli.trace=DEBUG. This will cause picocli to print some details, including exactly what command line args it received.

    I am guessing that the javaCLI wrapper script passes the parameters like this:

    java -cp myjar.jar:picocli-4.2.0.jar com.xxx.MainClass $@
    

    If that is the case it may be possible to fix the issue by ensuring the quotes are preserved when passing arguments to the java executable. Thanks to https://stackoverflow.com/a/39463371/1446916 for the idea of using printf to preserve the quotes:

    # attempt to ensure each argument keeps its original quoting
    ARGS=$( printf "%q " "$@" )
    
    java -cp myjar.jar:picocli-4.2.0.jar com.xxx.MainClass ${ARGS}
    

    If my guesses are incorrect please provide more details in the question.