Reputation: 71
I have a bash script which executes a Java Command and passes the space delimited String as an argument. Lets say the java class is "HelloWorld" and the required argument is passed as "-environment WIN XP". So the lines in my script are :
env = WIN XP
arg=" -environment $env"
javaCmd="java -Xmx2000m foo.bar.HelloWorld $arg"
$javaCmd
My HelloWorld class gets only the partial argument -environment WIN and throws an error because it is expecting -environment WIN XP as a whole with spaces. What are the ways in which I can make sure the entire String is treated as once without getting split at the whitespace.
Upvotes: 0
Views: 154
Reputation: 246847
I'm trying to put a command in a variable, but the complex cases always fail!
You need to use an array to preserve which elements contain whitespace:
env="WIN XP"
javaCmd=( java -Xmx2000m foo.bar.HelloWorld -environment "$env" )
"${javaCmd[@]}"
All the quotes above are necessary
Upvotes: 4
Reputation: 105
THere should be no space between =
and the name when assigning a variable. I would propose you use a different name than env
for a variable. Also the variable arg
isn't really necessary here. You can directly incorporate that in javaCmd
.
env="WIN XP"
javaCmd="java -Xmx2000m foo.bar.HelloWorld -environment $env"
$javaCmd
Upvotes: 2