I am developing a web application wherein I am using JSP as my front end and shell script as my back end. Thus I would be passing parameters from input JSP to the shell script via a Java Program(Business Layer). I would like to know how would I be able to pass parameters from Java to shell script and execute the same.Thank you.
Asked
Active
Viewed 2,717 times
0
-
Similar to this? http://stackoverflow.com/questions/5711084/java-runtime-getruntime-getting-output-from-executing-a-command-line-program – tjg184 Jun 18 '12 at 17:53
-
Use ProcessBuilder with the [command](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html#command(java.util.List)) method to pass arguments. – Denys Séguret Jun 18 '12 at 17:54
2 Answers
1
you can use ProcessBuilder
to pass parameter to shell script.
ProcessBuilder pb = new ProcessBuilder("shellscript", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory("myDir");
Process p = pb.start();

amicngh
- 7,831
- 3
- 35
- 54
-
Thank you for your reply.I have a question, Are "myArg1" and "myArg2" the arguments passed to the shell scripts. If that is the case, I am not getting the use of VAR1 and VAR2. Also if I need to do some processing in the shell script with the help of "myArg1" and "myArg2" and get some results, how would I transfer that result back to my Java program. I have analyzed about this in many forums but I am not able to find an answer. Could you please help me. – User Jun 18 '12 at 20:53
-
I have figured out the answer and I think this might be helpful for people – User Jun 18 '12 at 22:55
1
I have figured out the answer and I think this might be helpful for people. Please refer to the code
public static BufferedReader process() throws IOException
{
ProcessBuilder pb = new ProcessBuilder("/home/XXXX/Desktop/request.sh","Apple");
String line;
Process process=pb.start();
java.io.InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
return br;
}
Here "Apple" is the input parameter for the shell script and that will be stored in $1(environmental variable) and this could be accessed from shell script and when something needs to be sent from shell script to Java, echo from shell script and get that from process.inputStream()
in Java ..

Praveenkumar
- 24,084
- 23
- 95
- 173

User
- 401
- 2
- 8
- 15