7

I need to run a .sh file from my Java code with out passing any arguments. I already tried doing it with

Runtime.getRuntime().exec("src/lexparser.sh");

and

ProcessBuilder pb = new ProcessBuilder("src/lexparser.sh");
Process p = pb.start();

Both of the above methods didn't work. Is there any other method to run a .sh file form Java?

Tom
  • 16,842
  • 17
  • 45
  • 54
yAsH
  • 3,367
  • 8
  • 36
  • 67

2 Answers2

12
ProcessBuilder pb = new ProcessBuilder("src/lexparser.sh", "myArg1", "myArg2");
 Process p = pb.start();
 BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
 String line = null;
 while ((line = reader.readLine()) != null)
 {
    System.out.println(line);
 }
Biswajit
  • 2,434
  • 2
  • 28
  • 35
3

There are two things that are easy to miss:

  1. Path and CWD. The simplest way to ensure that the executable is found is to provide the absolute path to it, for example /usr/local/bin/lexparser.sh

  2. Process output. You need to read the process output. The output is buffered and if the output buffer gets full the spawned process will hang.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
  • I kept the .sh file in my project folder. My .sh file should read a file and update the contents of another file. It's working file when am running it directly from terminal but not from a java file – yAsH Mar 15 '13 at 09:25
  • +1 for the Path issue. I believe that there's an exec() method that can take in the working directory as the last argument (and I think you can null out the rest if n/a) – SeKa Mar 15 '13 at 09:28
  • @user2111009 I haven't spawned processes from Java in a long time, so I cannot give any more specific information than what I've already provided. Try setting the CWD explicitly from inside the script (using `cd`). – Klas Lindbäck Mar 15 '13 at 10:10