3

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?

  • 3
    I don't think this question is helped by the [tag:JavaScript] tag; edited to [tag:Java]. – David Thomas Nov 10 '12 at 15:17
  • using $1 in your bash script means that you read the first argument. as i understand it, you try to input your data through stdin instead. – devsnd Nov 10 '12 at 15:19
  • [dup?](http://stackoverflow.com/questions/525212/how-to-run-unix-shell-script-from-java-code) – Tim Pote Nov 10 '12 at 15:25

2 Answers2

1

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]
Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
1

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()); 
Sudhanshu Gupta
  • 1,889
  • 1
  • 17
  • 15