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?
This post talks about how you can execute a shell script from a Java program. If you have a shell script say test.sh then you can run it from a Java program using RunTime class or ProcessBuilder (Note ProcessBuilder is added in Java 5).
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);
}
There are two things that are easy to miss:
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With