We are trying to invoke Linux command history
from a Java program. We are able to invoke quite a few commands from Java, including date
and ls -l
without any issues. However, history
is failing with the java.io.IOException
. The sample source code follows:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class OSCommand {
public static void main(String[] args) throws Exception {
dumpCommandOutput("Date", new String[] {"date"});
// SUCCEEDS
dumpCommandOutput("Long Directory Listing", new String[] {"ls", "-l"});
// SUCCEEDS
dumpCommandOutput("Command History", new String[] {"history"});
// FAILS
}
protected static void dumpCommandOutput(String label, String[] cmdWithArgs) throws IOException {
System.out.println("Attempting to execute: " + label);
Process p = Runtime.getRuntime().exec(cmdWithArgs);
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str;
while((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
System.out.println("
");
}
}
Exception thrown
Exception in thread "main" java.io.IOException: Cannot run program "history": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at java.lang.Runtime.exec(Runtime.java:621)
at java.lang.Runtime.exec(Runtime.java:486)
at OSCommand.dumpCommandOutput(OSCommand.java:16)
at OSCommand.main(OSCommand.java:10)
Caused by: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
at java.lang.ProcessImpl.start(ProcessImpl.java:134)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 4 more
See Question&Answers more detail:os