1

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

8
  • Have you tried the obvious: ProcessBuilder pb2=new ProcessBuilder("/home/abhijeet/sample1.sh param1=abc param2=xyz");? Commented Jun 30, 2014 at 13:03
  • possible duplicate of difference between ProcessBuilder and Runtime.exec() Commented Jun 30, 2014 at 13:04
  • @SirTroll: i have read that , but that does't solve my problem,I tried it that way, that is for passing arguements to commands, not for shellscript Commented Jun 30, 2014 at 13:06
  • 1
    The code you "tried" would give you a syntax error. Commented Jun 30, 2014 at 13:11
  • 1
    You can use Apache commons exec library also. Commented Jun 30, 2014 at 13:13

1 Answer 1

4

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.