简体   繁体   中英

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 ?

像这样:

java -cp . Main "$@"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM