Reputation: 1857
I am calling a shell script from java code using :
ProcessBuilder pb2=new ProcessBuilder("/home/abhijeet/sample1.sh ");
Process script_exec = pb2.start();
Which runs successfully,But i need to pass some parameters to it , so I need to execute this script as :
param1=abc param2=xyz /home/abhijeet/sample1.sh
I have tried this code:
ProcessBuilder pb2=new ProcessBuilder("/home/abhijeet/sample1.sh ","param1=abc","param2="xyz");
But it did't work for me.How can i pass arguements to shell script while using Processbuilder for calling it?
Note:My question is about passing arguments to shellscript ,not to commands.i have read that suggested possible duplicate question , but that does't solve my problem,I tried it that way, that is for passing arguements to commands, not for shellscript
Upvotes: 1
Views: 8517
Reputation: 25380
You say you need to run the command:
param1=abc param2=xyz /home/abhijeet/sample1.sh
In this case, the "param1" and "param2" strings aren't command-line arguments. This is shell syntax to set the two environment variables param1
and param2
and then invoke sample1.sh
.
To accomplish this with ProcessBuilder
, you need to access the builder's environment variables:
ProcessBuilder pb2=new ProcessBuilder("/home/abhijeet/sample1.sh");
pb2.environment().put("param1", "abc");
pb2.environment().put("param2", "xyz");
Process script_exec = pb2.start();
As an alternative, the command that you're trying to run uses shell syntax, so you could pass it to a shell to execute it:
ProcessBuilder pb2=new ProcessBuilder(
"/bin/sh",
"-c",
"param1=abc param2=xyz /home/abhijeet/sample1.sh");
Process script_exec = pb2.start();
Upvotes: 4