Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Runtime Process Won't "Grep"

I'm executing some commands from the command line in my java program, and it appears that it doesn't allow me to use "grep"? I've tested this by removing the "grep" portion and the command runs just fine!

My code that DOESN'T work:

String serviceL = "someService";
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("chkconfig --list | grep " + serviceL);

Code that does work:

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("chkconfig --list");

Why is this? And is there some sort of correct method or workaround? I'm aware that I could just parse the entire output, but I would find it easier to do it all from the command line. Thanks.

like image 881
Max Avatar asked Oct 19 '11 17:10

Max


1 Answers

The pipe (like redirection, or >) is a function of the shell, and so executing it directly from Java won't work. You need to do something like:

/bin/sh -c "your | piped | commands | here"

which executes a shell process within the command line (including pipes) specified after the -c (in quotes).

So, here's is a sample code that works on my Linux OS.

public static void main(String[] args) throws IOException {
    Runtime rt = Runtime.getRuntime();
    String[] cmd = { "/bin/sh", "-c", "ps aux | grep skype" };
    Process proc = rt.exec(cmd);
    BufferedReader is = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line;
    while ((line = is.readLine()) != null) {
        System.out.println(line);
    }
}

Here, I'm extracting all my 'Skype' processes and print the content of the process input stream.

like image 95
Konstantin Yovkov Avatar answered Sep 27 '22 21:09

Konstantin Yovkov