javapiperuntime.exec

How to use pipes in a java Runtime.exec


I'm getting null as the output of this command line.

Process result = Runtime.getRuntime().exec(new String[]{"/usr/bin/find",baseDir+"/..","-type","f","|","/usr/bin/grep",filter1,"|","/usr/bin/grep",filter2,"|","/usr/bin/wc","-l"});
result.waitFor();
BufferedReader echo = new BufferedReader(new InputStreamReader(result.getInputStream()));
writer.print(echo.readLine());
echo.close();

Is it the pipes "|"?


Solution

  • To get the shell commands like |, use /bin/bash as your first argument to exec, -c as the second, and the entire string (including find, it's parameters and the pipe etc) as the third.

    Process result = Runtime.getRuntime().exec(new String[]{"/bin/bash", "-c", "/usr/bin/find " + baseDir+"/.. -type f | /usr/bin/grep " +filter1 + "| /usr/bin/grep "+filter2+" | /usr/bin/wc -l"});