Last days had some trouble with space characters used in file names and the consequences of passing parameters using those file names to Linux programs.
Consider the following example:
test1.sh:
cmdline="-DMyTest=\"1 2 3\" -some \"./Arguments.test\" -testpath=\"/my test\" \"my test\""
echo ----------------------------------------------
./test2.sh $cmdline
echo ----------------------------------------------
./test2.sh -DMyTest="1 2 3" -some "./Arguments.test" -testpath="/my test" "my test"
test2.sh:
echo Using '"$@"';
for p in "$@";
do
echo "[$p]";
done
Calling test1.sh, the result is:
----------------------------------------------
Using "$@"
[-DMyTest="1]
[2]
[3"]
[-some]
["./Arguments.test"]
[-testpath="/my]
[test"]
["my]
[test"]
----------------------------------------------
Using "$@"
[-DMyTest=1 2 3]
[-some]
[./Arguments.test]
[-testpath=/my test]
[my test]
– where the first part is an issue as it does not read my arguments as expected.
The solution was very simple, in the first call use
eval ./test2.sh $cmdline
instead. Although the solution is really simple, it was difficult to Google anything useful thus this post.
Finally found a hint in http://www.linuxjournal.com/content/bash-preserving-whitespace-using-set-and-eval
P.S. If you need to call a Linux shell command using Java – Runtime.exec() method, use an array as the input and DON’T try to wrap every argument in spaces. It works on Windows but not Linux.