简体   繁体   中英

How to pass arguments to a shell script using java?

I have written a code which calls a shell script:

 ProcessBuilder pb2=new ProcessBuilder("/home/abhijeet/sample1.sh");
 Process script_exec = pb2.start();
 pb2.redirectError();

Code works for me , as it executes script.

This script takes two arguements 1: input file 2: seqs , in a pattern like:

 sample1.sh -ip=abc.txt --seqs=20

Shell script is interactive one, which asks for many parameters , so i have changed it's code and i will pass those values as arguements to it. So complete format should be like:

db=abc outformat=1 threads=10 sample1.sh --ip=abc.txt --seqs=20

So how can i execute this script using java? Is there any other way to call a interactive script using java?

I recommend to use Apache Commons Exec , it helps to run external processes in multi-platform environment.

Here is the tutorial: http://commons.apache.org/proper/commons-exec/tutorial.html

Just pass the arguments in the ProcessBuilder constructor. Like this:

ProcessBuilder pb2=new ProcessBuilder("/home/abhijeet/sample1.sh", "-ip=abc.txt", "--seqs=20");

You can also use a List < String > instead.

You can try this:

 ProcessBuilder pb2=new ProcessBuilder("/home/abhijeet/sample1.sh --ip=abc.txt --seqs=20");
 Process script_exec = pb2.start();
 OutputStream in = script_exec.getOutputStream();
 in.write("abc".getBytes());
 in.write("1".getBytes());
 in.write("10".getBytes());
 in.flush();
 in.close();

This code writes abc, 1 and 10 to process input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM