Java Runtime Process Will Not Be "Grep"

I am executing some commands from the command line in my java program, and it seems that this does not allow me to use "grep"? I tested this by removing the “grep” part, and the command works just fine!

My code that DOES NOT work:

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

Code that works:

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

Why is this? And is there any correct method or workaround? I know that I can just parse all the output, but it would be easier for me to do all this from the command line. Thank.

+5
source share
3 answers

, ... ; chkconfig.

:

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

... grep? chkconfig java.

+6

(, >) , Java . - :

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

( ), -c ( ).

, , Linux.

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);
    }
}

"Skype" .

+8

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

or if you are using linux env just use grep4j

0
source

All Articles