how to execute a unix shell script from a java program

Hi All,

well , i am facing this problem.. i have tried a few sample codes but there isn't any solution . could anyone please give a sample code as of how to do this...

Please see the below details...and read the details carefully.

I have written some code, logic is

1)from UI we will get one file on window

2)from window that file will save on server i.e on /home/user01/trial1/csvfile.txt (This is successfully downloaded on the server)

3)that file we are passing to the script name-"omsSB.sh"
and output will save in csvfileout.txt

In below code everytnig is fine .From UI I am able to pass the tuple and also fetch the output file but iam unable to execute the omsSb.sh script

Question--> SCRIPT_NAME =./omsSb.sh
is it the correct command
or i need to right--- /home/user01/trial1/omsSb.sh. tried some of these like but script is not running.

This below code i have write in eclipse properties file , where i can mentioen the all the details of server.

 
TUPLE_FILE =
/home/user01/trial1/csvfile.txt

WORKING_DIRECTORY =/home/user01/trial1

SCRIPT_NAME =./omsSb.sh

OUTPUT_FILE =/home/user01/trial1/csvfileout.txt

Thanks

1) if you run :

./omsSb.sh

This suppose that you already are in the directory hosting that script

It also suppose that your user is granted (at least) to read that script (if you want to run it in the way mentionned above, you also must have execution right on it)

It also suppose that your script has the execution right (chmod +x yourscript).

If the execution right are not set for your file you can try to run it like :

sh ./omsSb.sh

(make sure you are in the right directory)

otherwise maybe you can give a try with :

SCRIPT_NAME = "sh /home/user01/trial1/omsSb.sh"
1 Like

If you are executing directly the script on unix, better replace variable SCRIPT_NAME with the absolute path of the script.

If you want to execute shell script or any system command then below code may help you.

    try {
        Process p = Runtime.getRuntime().exec("uname -a");
        // you can pass the system command or a script to exec command. here i used uname -a system command
        BufferedReader stdInput = new BufferedReader(new 
                InputStreamReader(p.getInputStream()));

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

        // read the output from the command
        String s="";
        
        while ((s = stdInput.readLine()) != null) {
            System.out.println("Std OUT: "+s);
        }
        
        while ((s = stdError.readLine()) != null) {
            System.out.println("Std ERROR : "+s);
        }
    
        
    } catch (IOException e) {
      
        e.printStackTrace();
    }

Thanks,
Kalai

Thas to all , for the help.

Code is working now .

changed the below path and its working

SCRIPT_NAME = "sh /home/user01/trial1/omsSb.sh"