Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run a bash script in java using input

Tags:

java

I'm trying to run a bash script file in Java program and I'm using this way:

Runtime rt = Runtime.getRuntime();

try {           
  Process proc = rt.exec("THE PATH FILE");        
  BufferedReaderinput=newBufferedReader(newInputStreamReader(proc.getInputStream()));
  String line=null;
  while((line=input.readLine()) != null) {
    System.out.println(line);
   }
} catch (IOException ex) {
  System.out.println(ex.toString());
}

but I'm using an input in my bash script as $1 when I'm running it from command line and I want to use it in my Java program to take the correct output . How can I do this in my Java program?

like image 388
Ibrahim Makhoul Avatar asked Aug 13 '26 01:08

Ibrahim Makhoul


2 Answers

Read the input in your Java app, then launch a new process that looks something like this:

bash myfile.sh arg[0] arg[1] arg[n]
like image 107
Mike Thomsen Avatar answered Aug 14 '26 15:08

Mike Thomsen


As suggested by Mike Thomsen, you can get the command line arguments into your java application and pass them on to the script file something like this.

StringBuilder cmdLineArgs = new StringBuilder();  

for(String arg:args){   //in case you may have variable number of arguments
    cmdLineArgs.append(arg).append(" ");
}

Now pass the arguments collected in cmdLineArgs to your script.

Process proc = rt.exec("YOUR SCRIPT " + cmdLineArgs.toString()); 
like image 39
Sudhanshu Gupta Avatar answered Aug 14 '26 13:08

Sudhanshu Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!