Search code examples
javacygwin

Running Shell Script at the command line


I am running a Shell script using cygwin.

Process p;
InputStream in;
BufferedReader br;
String line;
String cmd;
cmd = "D:/cygwin/bin/bash -c '/bin/test/app.sh" +three_ltr_id+""+mon_code+""+year_code+""+part_no+""+version_no+" '";
System.out.println("EXECUTING: " + cmd);
p = Runtime.getRuntime().exec(cmd);
in = p.getInputStream();
p.waitFor();
 br = new BufferedReader(new InputStreamReader(in));
 System.out.println("OUT:");
 while ((line = br.readLine()) != null) {
 System.out.println(line);
 System.out.println("SCRIPT EXECUTED PROPERLY");

This is showing EXECUTING and the commands that I passed to script.

If I go inside D:/cygwin/bin/test folder and run the same command it works.

When I run the same command at the command line it won't work.


Solution

  • You need to start reading the input from p.getInputStream() immediately, and keep reading it until there is no more. On Windows, there is little or no buffer in the pipe, and the process will hang once it is filled.

    Same is true for the error stream. You could launch threads to read both streams, or there's an option in the way you launch processes to combine regular output and errors, and you can just read them from there.