简体   繁体   中英

Passing args[] to java app with spaces

If you pass an arg to a java app via a bash script, and the arg contains whitespaces, how can you make the java app see the entire string as the arg and not just the first word? For example passing the following two args via bash to java:

var1="alpha beta zeta"
var2="omega si epsilon"

script.sh $var1 $var2

(inside script.sh)

#!/bin/bash
java -cp javaApp "$@"

(inside javaApp)

param1 = args[0];
param2 = args[1];

The values of my param variables in javaApp are getting only the words, not the entire lines:

"param1 is alpha"
"param2 is beta"

What can I change in the javaApp to see the entire string being passed in via args[] as the argument and not just the first word it encounters?

The problem is the way your shell script is written, not your Java program.

You need to quote the arguments:

script.sh "$var1" "$var2"

You should wrap the arguments in quotes when you call script.sh :

$ script.sh "$var1" "$var2"

These lines:

var1="alpha beta zeta"
var2="omega si epsilon"

don't actually include the quotes in var1 's and var2 's strings.

the problem is that you are merging the variables already when calling script.sh (and once they are merged, there is no way to split them again).

so do something like:

var1="alpha beta zeta"
var2="omega si epsilon"

script.sh "$var1" "$var2"

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