0

I'm trying to get the output of grep linux shell command in java by using process builder. But i got a stuck in this case. Please help me. Thank in advice!

    String[] args = new String[7];
    args[0] = "/bin/bash";
    args[1] = "-c";
    args[2] = "grep";
    args[3] = "-n";
    args[4] = "-e";
    args[5] = "KERNELVERSION";
    args[6] = kernelFilePath.trim();

ProcessBuilder pb;
    Process process = null;
    try {
        pb = new ProcessBuilder(args);
        pb = pb.directory(new File(directory));
        pb.inheritIO();
        pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        pb.redirectError(ProcessBuilder.Redirect.INHERIT);
        process = pb.start();
        process.waitFor();
    } catch (IOException | InterruptedException e) {
        System.out.println("executeCmdWithOutput() exception : " + e.toString());
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

==> Error:

Usage: grep [OPTION]... PATTERN [FILE]...

Try 'grep --help' for more information.

I tried the command in bash and it worked fine:

grep -n -e KERNELVERSION ..../Makefile
1
  • Full command must be passed as single argument to bash: args[2] = "grep -n -e KERNELVERSION " + kernelFilePath.trim(); Commented Nov 9, 2017 at 11:16

2 Answers 2

2

Have you tried change the args[2] as full command?

Also, you can use pgrep, it does not require you to use pipe.

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

1 Comment

How will pgrep help? It is for grepping for running processes, not for data in a file.
0

You don't need to explicitly run /bin/bash in order to execute the grep process. Just call it directly and ProcessBuilder will run it:

String[] args = {"grep", "-n", "KERNELVERSION", kernelFilePath.trim()};

Also, you don't need to use the -e option, unless there are multiple patterns that you are searching for.

If you really wanted to run grep in /bin/bash:

String[] args = {"/bin/bash", "-c", "grep -n KERNELVERSION " + kernelFilePath.trim()};

passes a single argument to bash containing the full command and arguments to execute.

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.