How to execute /bin/sh with commons-exec?

yegor256 picture yegor256 · Feb 22, 2011 · Viewed 9.3k times · Source

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?

Answer

Christoffer Hammarström picture Christoffer Hammarström · Feb 22, 2011

According to the FAQ "It is recommended to use CommandLine.addArgument() instead of CommandLine.parse()".

So try

CommandLine commandLine = new CommandLine("/bin/sh");
commandLine.addArgument("-c");
commandLine.addArgument("echo test", false); // false is important to prevent commons-exec from acting stupid
executor.execute(commandLine);