This is what I'm doing:
import org.apache.commons.exec.*;
String cmd = "/bin/sh -c \"echo test\"";
new DefaultExecutor().execute(CommandLine.parse(cmd));
This is the output:
/bin/sh: echo test: command not found
What am I doing wrong?
This is what I'm doing:
import org.apache.commons.exec.*;
String cmd = "/bin/sh -c \"echo test\"";
new DefaultExecutor().execute(CommandLine.parse(cmd));
This is the output:
/bin/sh: echo test: command not found
What am I doing wrong?
According to the FAQ "It is recommended to use
CommandLine.addArgument()
instead ofCommandLine.parse()
".So try
The command doesn't work because commons-exec doing unnecesary quoting of all arguments, which have space or quote.
This unnecessary quoting of arguments is controlled by
handleQuoting
flag of each argument. If you create theCommandLine
object using it's constructor andaddArgument
methods, you can set this flag tofalse
.Like this:
(The important part is
false
as second argument ofaddArgument
method)And it works! But... it is unconvinient to construct command line manually instead of having it defined in some config file.
CommandLine.parse
always sets thehandleQuoting
flag to true! Who knows why...I wrote this small helper method using reflection to fix "bad"
CommandLine
object, created usingCommandLine.parse
.It just clones the given
CommandLine
, setting each argument'shandleQuoting
flag tofalse
. The methodFieldUtils.readField
is from commons-lang3 library, but you can use plain reflection if you want.It allows to parse command line and still successfully execute it.
I can reproduce your problem from a shell command line:
I'd say you should try to not quote the command.
This one works for me:-