Reputation:
I have a shell script named test.sh
in /tmp/padm
folder.
In that shell script I have a single statement
echo "good"
I am trying to run the shell script using Java code.
String cmd=("/tmp/padm/.test.sh");
Runtime rt = Runtime.getRuntime();
Process pr=rt.exec(cmd);
But my problem is that I am not able to see "good" which is the output of the shell script.
How can I get the script to run?
Upvotes: 2
Views: 6975
Reputation: 1499
Try this, it will definitely works.
Shell Script test.sh code
#!/bin/sh
echo "good"
Java Code to execute shell script test.sh
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(new String[]{"/bin/sh", "/tmp/padm/.test.sh"});
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
Upvotes: 1
Reputation: 23950
This is a duplicate of Need sample java code to run a shellscript.
The example program in my answer there does print out standard error and standard output (the example program is added a bit later).
Please note that the streamGobblers are running in separate threads to prevent execution problems due to full input/output buffers.
If you wish you can of course let the StreamGobblers store the output in lists, and retrieve the lists after the process executed in stead of dumping it directly on stdout.
Upvotes: 0
Reputation: 7486
You could get the command output with the following piece of code. Hope this helps.
Process process = Runtime.getRuntime().exec(cmd);
String s = "";
BufferedReader br = new BufferedReader(new InputStreamReader(process
.getInputStream()));
while ((s = br.readLine()) != null)
{
s += s + "\n";
}
System.out.println(s);
BufferedReader br2 = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while (br2.ready() && (s = br2.readLine()) != null)
{
errOutput += s;
}
System.out.println(errOutput);
Upvotes: 4
Reputation: 5787
process.getErrorStream();
process.getOutputStream();
is the right approach as pointed out by oxbow_lakes.
Additionally make sure that you exec /bin/sh
with the shell script location as an argument.
Upvotes: 1
Reputation: 134260
When you say "on the terminal" what do you mean? If you want to see output/error from the process you'll need to use:
process.getErrorStream();
process.getOutputStream();
Other than that, there's no problem I can see from your use of Runtime.exec
to invoke a shell script
Upvotes: 1
Reputation: 399723
That won't work. You must add either a "hash bang" to the first line of the script, to tell Linux that it must use a suitable interpreter (e.g. bash) to interpret the script, or run it through bash explicitly from Java.
Upvotes: 1