Running shell script from java

Hello All,

Hope all is well. I was trying to scratch my head here with simple problem of running Shell script in Java. I tried to google and look through forums but was unable to understand how to solve it.

Here is my simple Java class, which resides in different directory then my shell script. So I am trying to change path and run the shell script located there. Also, I am passing parameters to shell script from Java as arguments. But for some reasons ...I am getting IOException . Could you please suggest what I am I missing here.

 
public class test4
{
  public static void main(String [] args) throws IOException
        {
        Process P;
        P = Runtime.getRuntime().exec("cd ~/apps/source");
        P = Runtime.getRuntime().exec("test.sh \"" + args[0]+ "\" \"" + args[1] + "\" \"" + args[2]+"\" \"" + args[3] + "\" \"null\"");
         }
}

Thanks in advance,

Sam

(A) Instead of the "cd" command and then the script execution, just put the absolute path of the script.
(B) Seems like "~" is not interpreted properly, so use the actual path devoid of "~".

$ 
$ # Display the contents of the shell script
$                                           
$ cat /home/r2d2/data/unix/test.sh
echo "First parameter   = $1" > test.log
echo "Second parameter  = $2" >> test.log
echo "Third parameter   = $3" >> test.log
echo "Fourth parameter  = $4" >> test.log
echo "Fifth parameter   = $5" >> test.log

$ 
$ # Display the contents of the java program
$                                           
$ cat test4.java
import java.io.IOException;
public class test4
{
  public static void main(String [] args) throws IOException
  {
     Process P;
     P = Runtime.getRuntime().exec("/home/r2d2/data/unix/test.sh \"" + args[0]+ "\" \"" + args[1] + "\" \"" + args[2]+"\" \"" + args[3]+ "\" \"null\"");
  }
}
$
$ # Compile
$
$ javac test4.java
$
$ # Execute, passing the input parameters
$
$ java test4 ant bat cat dog eel
$
$ # Verify that it ran successfully
$
$ cat test.log
First parameter   = "ant"
Second parameter  = "bat"
Third parameter   = "cat"
Fourth parameter  = "dog"
Fifth parameter   = "null"
$
$

Hope that helps,
tyler_durden

Hello Tyler,

Thanks so very much for taking time out and testing it out. Really do appreciate it.

I was able to resolve the problem. Problem was that my shell didn't have execute rights on it and hence java was unable to trigger it. For whatever reasons Java didn't trap it!! Am I missing something here ?

BTW, "~" worked okay and Java was able to find shell script with "~"(tilda) in it.

Thanks again for help and enjoy sunny weekend.

  • Sam