6

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.

0

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

Comments

6

You're trying to use piping which is a function of the shell ... and you're not using a shell; you're exec'ing the chkconfig process directly.

The easy solution would be to exec the shell and have it do everything:

Process proc = rt.exec("/bin/sh -c chkconfig --list | grep " + serviceL);

That being said ... why are you piping to grep? Just read the output of chkconfig and do the matching yourself in java.

2 Comments

No reason that I can't match in Java. I just figured it would be faster to write out the grep than to parse the output. I'm relatively new with Linux so I was unaware that grep was a function of the shell. Thanks!
@Max: grep is not a shell builtin, the pipe | is a shell syntax feature.
0

String[] commands = { "bash", "-c", "chkconfig --list | grep " + serviceL }; Process p = Runtime.getRuntime().exec(commands);

or if you are in a linux env just use grep4j

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.