Script and java shell options

I wrote a script run.sh below to call the java class:

java -cp . Main $1 $2 $3 $4

Here is my java class (it just displays args):

public class Main {
    public static void main(String[] args) {
        for (String arg : args) {
            System.out.println(arg);
        }
    }
}

This works if I do not try to pass a parameter containing a space. For instance:

./run.sh This is "a test"

will display:

This
is
a
test

How can I change my shell script and / or change the syntax of the parameters to pass the parameter "test" unmodified?

+3
source share
2 answers

Like this:

java -cp . Main "$@"
+7
source

You must also mask each parameter in the script:

java -cp . Main "$1" "$2" "$3" "$4"

Now parameter 4 should be empty, and $ 3 should be a "test".

To check, try:

#!/bin/bash
echo 1 "$1"
echo 2 "$2"
echo 3 "$3"
echo 4 "$4"
echo all "$@"

and name him

./params.sh This is "a test" 
1 This
2 is
3 a test
4 
all This is a test
+3
source

All Articles