Search code examples
javaeclipseshellstoreprintln

How to save output values to a String variable?


Please excuse me because I am Korean and am not good at English.

I want to store the output of shell scripts in String.

But they couldn't find a way. What should I do?

package dbUpdate;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;

public class ShellCommander {

    static Scanner sc = new Scanner(System.in);
    static String carSSID;
    static String target;
    static String IPAddress;

    public static void main(String[] args) throws Exception {


        String command = "/usr/local/bin/docker ps";

        shellCmd1(command);
    }


    public static void shellCmd1(String command) throws Exception {
        String line;
        ProcessBuilder pb = new ProcessBuilder(command.split("\\s+"));
        pb.inheritIO();
        Process p = pb.start();
        p.waitFor();
    }

}

Solution

  • you have to use Streams to get the standard out (output of your script) and standard error. Have a look at my wiki article "Proper handling of the ProcessBuilder". The handling of the Streams is described there.