0

Caveat - I'm not a Java programmer, just a hacker!

I wrote a Java-based Gradle plugin that executes shell commands, something like this, which in this case, are Git commands.

    BufferedReader execShellCmd(final String cmd) {
        BufferedReader br = null;
        ProcessBuilder pb = new ProcessBuilder();
        if (isWindows()) {
            pb.command("cmd.exe", "/c", cmd);
        }
        else {
            pb.command("sh", "-c", cmd);
        }
        try {
            Process p = pb.start();
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));

            exitVal = p.waitFor();
            if (exitVal > 0) {
                System.out.printf("%s failed, err no: %d", cmd, exitVal);
            }
        }
        catch (IOException e){
            System.out.println("ERROR: I/O exception");
            e.printStackTrace();
        }
        catch (InterruptedException e){
            System.out.println("ERROR: Interrupt exception");
            e.printStackTrace();
        }
        return br;
    }

    ...
    cmd = "if [[ -n $(git status -s) ]] ; then filelist=`git status -s` ; git commit -a -m \""+commitMsg+"\"; git push origin "+getSourceBranch()+":"+getSourceBranch()+" ; else echo \"No changes detected\"; fi";
    execShellCmd(cmd);

How can I print out the output of the cmd I'm passing in? I'm not talking about the result, where pass == 0, and fail > 0, which is exitVal in my code.

Chris F
  • 14,337
  • 30
  • 94
  • 192
  • 2
    `execShellCmd` returns a `BufferedReader`. So just read it from there? What's wrong exactly? – Sweeper May 09 '23 at 02:50
  • 1
    Something like [this](https://stackoverflow.com/questions/25377355/processbuilder-cannot-run-bat-file-with-spaces-in-path/25377564#25377564) or [this](https://stackoverflow.com/questions/12869175/run-another-java-program-from-within-a-java-program-and-get-outputs-send-inputs/12869233#12869233)? – MadProgrammer May 09 '23 at 03:10

0 Answers0