title: How to execute a bash script from java program
body: <p>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 </p>
  
  <pre><code>Runtime.getRuntime().exec(PathToScript);
  </code></pre>
  
  <p>It doesn't work either.</p>
  
  <pre><code>public class test1 {
  public static void main(String a[]) throws InterruptedException, IOException {
  
      List&lt;String&gt; commands = new ArrayList&lt;String&gt;();
      List&lt;String&gt; commands1 = new ArrayList&lt;String&gt;();
  
      commands.add("/Path/To/Script/skrypt3.sh");
      commands.add("&gt; /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);
      }
  
  }
  }
  </code></pre>
  
  <p>And here is the script I try to execute. It works like a charm when I run it directly from terminal.</p>
  
  <pre><code>#!/bin/bash          
  drozer console connect &lt;&lt; EOF &gt; /dev/ttys002
  permissions
  run app.package.info -a com.mwr.example.sieve
  exit
  EOF
  </code></pre>