Andreas said:
Wayne said:
we want to try execute a bash command from java but, I need to insert
in command a double quotes example:
Process p = rt.exec( "echo \"Te st\" " );
but the bash refuse a " value.
That command runs the "echo" command, not bash!
Also you need to pass the arguments to the command differently.
Use a shell like bash to use quoting:
Process p = rt.exec(
new String[]{"bash", "-c", "echo \"hello, world!\""} );
should do it.
-Wayne
Echo is also a separate command, but as such it needs no special
argument escaping:
Process p = rt.exec(new String[]{"echo", "hello, world!"} );
If you use any newer than stone aged java versions (1.5 and up), you
can also make it shorter:
Process p = rt.exec("echo", "hello, world!");
If you don't need to process backslash escapes, quotes, and
so on, using echo is easier. However I don't think that
your "modern stone aged" version will work, did you try it?
javac 1.6.0_05 complained when I tried, and the 1.6 API (javadocs)
don't list that as a legal version of Runtime.exec() either.
Also, just using echo as the command wouldn't permit parsing of
the argument string as the OP apparently wanted. You're right,
you don't need to parse "hello, world!" but you would need bash
or some shell to parse a more complex string including shell
variables, wildcards, etc. Interestingly the bash built-in
echo command has different semantics than /bin/echo command.
As a matter of portability printf should be used instead
anyway:
String arg = "Hello, \"World\"!";
Process p = rt.exec( new String[]{"bash", "-c",
"printf \"%s\\n\" " + arg} );
However that is uglier.
-Wayne