Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java ProcessBuilder to Execute a Piped Command

I'm trying to use Java's ProcessBuilder class to execute a command that has a pipe in it. For example:

ls -l | grep foo 

However, I get an error:

ls: |: no such file or directory 

Followed by:

ls: grep: no such file or directory 

Even though that command works perfectly from the command line, I can not get ProcessBuilder to execute a command that redirects its output to another.

Is there any way to accomplish this?

like image 477
user455889 Avatar asked Sep 23 '10 07:09

user455889


People also ask

How does Processbuilder work in Java?

Constructs a process builder with the specified operating system program and arguments. This is a convenience constructor that sets the process builder's command to a string list containing the same strings as the command array, in the same order.

How do you execute a Process in Java?

Process process = Runtime. getRuntime(). exec("processname"); Both of these will code snippets will spawn a new process, which usually executes asynchronously and can be interacted with through the resulting Process object.


1 Answers

This should work:

ProcessBuilder b = new ProcessBuilder("/bin/sh", "-c", "ls -l| grep foo"); 

To execute a pipeline, you have to invoke a shell, and then run your commands inside that shell.

like image 106
dogbane Avatar answered Sep 21 '22 09:09

dogbane