Reputation: 33
I am currently attempting to make a bash script that executes a Java main class with a path to an archive file as an argument. I want to make sure that it can handle spaces in that path, which is giving me a bit of a headache.
I want to set that path as an environment variable and call it when I execute the main class, so the script looks something like this:
export ArgPath='/Foo Path/foo.zip'
$JAVA_HOME/bin/java -cp ./foo.jar foopackage.main -a $ArgPath
Unfortunately, when I execute this in Bash, the command comes out like this:
/foo_Java_Home/bin/java -cp ./foo.jar foopackage.main -a /Foo Path/foo.zip
Java arguments can't have spaces. Java treats "/Foo" and "Path/foo.zip" as two separate arguments. Okay, that's not a problem. Java can handle arguments with spaces. I need to find some way to get double or single quotes around it. I'll try to escape double quotes around the path. The script now looks like this:
export ArgPath='\"/Foo Path/foo.zip\"'
$JAVA_HOME/bin/java -cp ./foo.jar foopackage.main -a $ArgPath
Bash gives me this...
/foo_Java_Home/bin/java -cp ./foo.jar foopackage.main -a '\"/Foo' 'Path/foo.zip\"'
...which still causes Java to treat them as two separate arguments (not to mention that it wouldn't work as a single argument anyway). I've tried about every combination and permutation of using single quotes, double quotes, and escaping single quotes/double quotes/spaces I can think of. Is there any way to provide the desired output of
'/Foo Path/foo.zip'
or "/Foo Path/foo.zip"
In Bash? For that matter, is it possible to get Bash to accept an arbitrary string literal without trying to add anything to it in circumstances like these? Escaping characters doesn't seem to work, so that may be the only option if it's possible.
Thanks in advance.
Upvotes: 1
Views: 5187
Reputation: 753525
Enclose the variable in double quotes in the command invocation:
export ArgPath='/Foo Path/foo.zip'
$JAVA_HOME/bin/java -cp ./foo.jar foopackage.main -a "$ArgPath"
Note that this applies generally to invoking any command (not just Java). If an argument contains spaces (etc.), enclose it in quotes (single or double). When the argument is in a variable, use double quotes.
Upvotes: 4