How to execute bash script from java program

I want my Java program to execute a bash script and return the result back to Java. The trick my script starts some kind of "interactive session", and I suppose that's why my Java application freezes (introduces an infinite loop, I suppose). Here is the code that I use to execute the script, for this I use ProcessBuilder. I also tried

Runtime.getRuntime().exec(PathToScript);

It doesn't work either.

public class test1 {
public static void main(String a[]) throws InterruptedException, IOException {

    List<String> commands = new ArrayList<String>();
    List<String> commands1 = new ArrayList<String>();

    commands.add("/Path/To/Script/skrypt3.sh");
    commands.add("> /dev/ttys002");



    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.redirectErrorStream(true);
    try {

        Process prs = pb.start();
        Thread inThread = new Thread(new In(prs.getInputStream()));
        inThread.start();
        Thread.sleep(1000);
        OutputStream writeTo = prs.getOutputStream();
       writeTo.write("oops\n".getBytes());
        writeTo.flush();
        writeTo.close();

    } catch (IOException e) {
        e.printStackTrace();

    }
}
}

class In implements Runnable {

private InputStream is;

public In(InputStream is) {
    this.is = is;
}

@Override
public void run() {
    try {
        byte[] b = new byte[1024];
        int size = 0;
        while ((size = is.read(b)) != -1) {



            System.out.println(new String(b));
        }
        is.close();
    } catch (IOException ex) {
        Logger.getLogger(In.class.getName()).log(Level.SEVERE, null, ex);
    }

}
}

And here is the script I'm trying to execute. It works like a charm when I launch it directly from the terminal.

#!/bin/bash          
drozer console connect << EOF > /dev/ttys002
permissions
run app.package.info -a com.mwr.example.sieve
exit
EOF
+4
source share
1 answer

You should not try to add redirection commands as part of the command name:

commands.add("/Path/To/Script/skrypt3.sh");
commands.add("> /dev/ttys002");
ProcessBuilder pb = new ProcessBuilder(commands);

redirectOutput, - :

tty = new File("/dev/ttys002");
ProcessBuilder pb = new ProcessBuilder("/Path/To/Script/skrypt3.sh")
    .redirectOutput(ProcessBuilder.Redirect.appendTo(tty))
    .redirectError(ProcessBuilder.Redirect.appendTo(tty))
    .start();

, , bash script , , Java.

. .

+1

Source: https://habr.com/ru/post/1619326/


All Articles