Sohail Khan
Sohail Khan

Reputation: 289

Unable to run Shell Script

Hi i am trying to run shell script from following code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

 public class ScriptTest {
     public static void main(String[] args){


    BufferedReader stdErr=null;
    BufferedReader stdIn=null;
    try{   
    System.out.println("In Script");
    String[] commands= {"ls"};
    Process process  = Runtime.getRuntime().exec("/mobilityapps/testScript/testScript.sh");
    stdIn=  new BufferedReader(new InputStreamReader(process.getInputStream()));        
    stdErr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    String inline= stdIn.readLine();
    String errline =stdErr.readLine();
    System.out.println("*Inline*"+inline);
    System.out.println("*Errline*"+errline);
    while(inline!=null){
        System.out.println(inline);
        inline=stdIn.readLine();
    }
    while(errline!=null){
        System.out.println(errline);
        errline=stdErr.readLine();
    }
    System.out.println("Process Exit Value: "+process.waitFor());
    }catch(Exception excp){
        excp.printStackTrace();
    }
}

}

The script i am trying to call is

CURRDATE=`date '+%d%b%Y'`
TIMESTAMP=`date '+%H:%M'`
BASE_PATH=/mobilityapps/testScript
LOGFILE=${BASE_PATH}/logs_${CURRDATE}_${TIMESTAMP}.log
echo ${CURRDATE} ${TIMESTAMP}>>${LOGFILE}

All both the script and Java program are in the same directory. When i run testScript.sh from PUTTY it runs fine

But when i run from Java program Process Exit Value is 255

Can anyone suggest the changes?

Upvotes: 0

Views: 677

Answers (1)

OscarSan
OscarSan

Reputation: 463

Try replacing the path

    Runtime.getRuntime().exec("/mobilityapps/testScript/testScript.sh");

with

    Runtime.getRuntime().exec("./mobilityapps/testScript/testScript.sh");

If you just use / at the begining, it means that it's a absolute path. Using '.' indicates that is a relative path.

Upvotes: 2

Related Questions