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.
-
Similar to this? stackoverflow.com/questions/5711084/…tjg184– tjg1842012-06-18 17:53:42 +00:00Commented Jun 18, 2012 at 17:53
-
Use ProcessBuilder with the command method to pass arguments.Denys Séguret– Denys Séguret2012-06-18 17:54:42 +00:00Commented Jun 18, 2012 at 17:54
Add a comment
|
2 Answers
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();
2 Comments
User
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
I have figured out the answer and I think this might be helpful for people
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 ..