79267450

Date: 2024-12-10 08:14:32
Score: 1.5
Natty:
Report link

@John Feminella's answer is awesome, but there is a problem when commands contain | (linux pipe).

So based on his answer, I give a new one:

Runtime r = Runtime.getRuntime();
String command = "ls /etc | grep release";
String[] cmd = {
  "/bin/sh",
  "-c",
  command,
};

Process p = r.exec(cmd);
p.waitFor();
BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";

while ((line = b.readLine()) != null) {
  System.out.println(line);
}

b.close();
Reasons:
  • Has code block (-0.5):
  • User mentioned (1): @John
  • Low reputation (1):
Posted by: kougazhang