Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a .sh file from Java? [duplicate]

Tags:

java

shell

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?

like image 905
yAsH Avatar asked Mar 15 '13 09:03

yAsH


People also ask

What is .sh file in 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).


2 Answers

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);
 }
like image 121
Biswajit Avatar answered Oct 15 '22 07:10

Biswajit


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.

like image 27
Klas Lindbäck Avatar answered Oct 15 '22 09:10

Klas Lindbäck