Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script and java parameter

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 ?

like image 367
Arnaud Avatar asked Dec 13 '22 02:12

Arnaud


2 Answers

Like this:

java -cp . Main "$@"
like image 157
Ignacio Vazquez-Abrams Avatar answered Dec 23 '22 07:12

Ignacio Vazquez-Abrams


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
like image 41
user unknown Avatar answered Dec 23 '22 07:12

user unknown