Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I would like my Java program to execute a bash script and return the output back to Java. The trick is my script starts some sort of 'interactive session' and I suppose that is why my Java application freezes (Enters an infinite loop I suppose). Here is the code I use to execute the script, I use ProcessBuilder in order to do that. 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 try to execute. It works like a charm when I run it directly from terminal.

#!/bin/bash          
drozer console connect << EOF > /dev/ttys002
permissions
run app.package.info -a com.mwr.example.sieve
exit
EOF
share|improve this question
    
Have you tried adding bash or /bin/bash before the script file (either in ProcessBuilder or Runtime)? – fedterzi 16 hours ago
    
I just tried, with no results. The problem is that it throws 'command not found' exception. I know those are my custom commands, but why java needs to process each command which is in the script. Let's just run that in terminal. Is there any way to do that? – DanoPlurana 16 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.