Thursday, December 13, 2012

Run Bash Script Using Java And Get Debug And Error Output

String command = "sudo /usr/bin/some_name.sh";
System.out.println("runBashScriptCommand: " + command);
try {
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(command);
    printBufferedReaderOutputFromProcess(process);
    process.waitFor();
    return "true";
} catch (Exception ex) {
    System.out.println("EX:" + ex.toString());
    return ex.toString();
}

private void printBufferedReaderOutputFromProcess(Process p) {
    try {
        String s = null;
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        // read the output from the command
        System.out.println("\n\npHere is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }
        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (Exception ex) {
        System.out.println("printBufferedReaderOutputFromProcess:" + ex.toString());
    }
}

No comments:

Post a Comment