Link to home
Start Free TrialLog in
Avatar of Amit
AmitFlag for United States of America

asked on

Running a unix shell script through a java code

Hi,

I have a little java program that loads a file into a database. Now I need to insert a shell script in this java program or rather

I need to run a little shell command say ls -l through a java program. Any ideas or sample code

thanks
-amit
Avatar of Venabili
Venabili
Flag of Bulgaria image

Had you tried the standard way :
Process p = Runtime.getRuntime().exec("ls -l");

See http://www.devdaily.com/java/edu/pj/pj010016/pj010016.shtml for a way to handle the output and some explanations.
If it is an external command - use http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#exec(java.lang.String[]) and start the sh or bash before invoking the actual script...
And an example how to use it: http://www.exampledepot.com/egs/java.lang/Exec.html
SOLUTION
Avatar of basav_com
basav_com
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
basav_com,

When someone had already proposed a solution and you want to mention it also, you should be giving credit to the first expert. We all try to help - let's work as a team and not as people that do not care for each other. Don't you think this will work better?

:) V
Avatar of Amit

ASKER

Hi experts,

Since I am a newbie. Could you please send me a code or something

I need to do the following using java in Unix

1. cd /alpha/beta
2. ls -t xyz* | head -1
3. And then print the output of step 2

I tried the sample codes but couldn't go far

thanks
-anshu
Hi amit,
As Venabili has mentioned about the Runtime class, Pls credit all the points to her only.
You can put above 3 steps in a single step as:
ls /alpha/beta -t xyz* | head -1  --- Once you execute this one thru Process p=Runtime.getRuntime().exec("ls /alpha/beta -t xyz* | head -1");
Read the process inputstream p.getStream() and then print it.
OR
Create a temporary file(shell script) with the above commands and then execute that file.

Hi Venabili,
Ok sure. I will follow your suggestion. :)


anshuma,

Post the code that you tried and what is the result that you see and we will help you fix it.

basav_com,

It's not for the points. Split would be just fine. (let's just first help the asker)
Avatar of Amit

ASKER

Here's the code

import java.io.*;

public class ShellScript {

    public static void main(String args[]) {

        String s = null;

        try {
           
          // run the Unix "ps -ef" command
           
         
           

           
            Process p = Runtime.getRuntime().exec("cd

/bia/opt/MicroStrategy");
           
            BufferedReader stdInput = new BufferedReader(new
                 InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new
                 InputStreamReader(p.getErrorStream()));

            // read the output from the command
           
            System.out.println("Here is the standard output of the

command:\n");
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
           
            // read any errors from the attempted command

            System.out.println("Here is the standard error of the command

(if any):\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
           
            System.exit(0);
        }
        catch (IOException e) {
            System.out.println("Error - Details are below ");

            e.printStackTrace();
            System.exit(-1);
        }
    }
}

-------------------------------------------

Here's the error message


Error - Details are below
java.io.IOException: Cannot run program "cd": java.io.IOException: error=2, No such file or directory
        at java.lang.ProcessBuilder.start(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at ShellScript.main(ShellScript.java:17)
Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
        at java.lang.UNIXProcess.<init>(Unknown Source)
        at java.lang.ProcessImpl.start(Unknown Source)
        ... 5 more

This is because cd is internal command. The ls will work as described above but for cd you need somewhat more special treatment.

You will need to do it through the Process output stream. Something like this (if /bin is the initial working directory and if you want to use bash - change the paths if needed) This will behave as if you are typing on the console

Let me know if you need more assistance with this

PS: Why you need to do the cd at all - can't you just invoke the commands with giving the full path to the directory?
File workDirectory = new File("/bin"); 
Process process = null; 
try { 
   process = runtime.getruntime().exec("/bin/bash", null, workDirectory ); 
} 
catch (IOException e) { 
   e.printStackTrace(); 
} 
if (process != null) { 
   BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); 
   PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())), true); 
   out.println("cd /bia/opt/MicroStrategy"); 
   out.println("pwd"); // this will print where you are. 
   //other commands here
   try { 
      process.waitFor(); 
      in.close(); 
      out.close(); 
      process.destroy(); 
   } 
   catch (Exception e) { 
      e.printStackTrace(); 
   } 
}

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Amit

ASKER

Hi,

I ran the following code but it didn't do anything and it looked like nothing was happening. I waited for 3-4 minutes before I killed it :-(

thanks
-anshu

import java.io.*;

public class ShellScript {

    public static void main(String args[])

    {





File workDirectory = new File("/bin");
Process process = null;
try {
   process = Runtime.getRuntime().exec("/bin/bash", null, workDirectory );
}
catch (IOException e) {
   e.printStackTrace();
}
if (process != null) {
   BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
   PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())), true);
   out.println("cd /bia/opt/MicroStrategy");
   out.println("pwd"); // this will print where you are.
   //other commands here
   try {
      process.waitFor();
      in.close();
      out.close();
      process.destroy();
   }
   catch (Exception e) {
      e.printStackTrace();
   }
}


}

}
See my last comment please. :) You need this comment at the beginning of the try-catch for the closing
      String line; 
      while ((line = in.readLine()) != null) { 
         System.out.println(line); 
      }

Open in new window

Avatar of Amit

ASKER

Thanks and sorry for not watching your last comment. it seems better but still its not getting stopped moreover this is the output that I get

so its not printing
out.println("cd /bia/opt/MicroStrategy");
out.println("pwd"); // this will print where you are.

sorry for asking so many questions I am not good in java but I really need to get few things done. If you are exhausted then I can award points and close this question

______________________________________________________
-bash-3.00$ /usr/bin/java ShellScript
/bia/opt/MicroStrategy

[4]+  Stopped                 /usr/bin/java ShellScript