4

I have written the script run.sh below for calling a java class :

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

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

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

This is working unless I try to pass a parameter containing a space. For example :

./run.sh This is "a test"

will display :

This
is
a
test

How could I modify my shell script and/or change my parameter syntax to pass the parameter "a test" unmodified ?

2 Answers 2

9

Like this:

java -cp . Main "$@"
Sign up to request clarification or add additional context in comments.

1 Comment

It might help if you explained why that works. This is a pretty contrived example. That may not be exactly what he wants to do in the end.
5

You have to mask every parameter in the script as well:

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

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

To verify, try:

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

and call it

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

2 Comments

The fact that parameter 4 is the empty string is annoying because the java program will receive a wrong number of parameters (4 while the user passed only 3). I think Ignacio's answer is better, thanks anyway.
@SuperChafouin: Oh, I see, my test wasn't accurate. I thought the "$@" would consume the masking, after seeing the output of my test, but I guess it is the last echo, which consumes the quotes, just like the Java program does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.