0

How can I call a shell script through java code? I have writtent the below code. I am getting the process exit code as 127. But it seems my shell script in unix machine is never called.

String scriptName = "/xyz/downloads/Report/Mail.sh";
String[] commands = {scriptName,emailid,subject,body};
Runtime rt = Runtime.getRuntime();
Process process = null;
try{
    process = rt.exec(commands);
    process.waitFor();
    int x = process.exitValue();
    System.out.println("exitCode "+x);
}catch(Exception e){
    e.printStackTrace();
}
dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
chandan
  • 19
  • 6

2 Answers2

0

From this post here 127 Return code from $?

You get the error code if a command is not found within the PATH or the script has no +x mode. You can have the code below to print out the exact output

BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String s= null;
        while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }

BufferedReader stdOut = new BufferedReader(new InputStreamReader(process. getErrorStream()));
        String s= null;
        while ((s = stdOut.readLine()) != null) {
                System.out.println(s);
            }
Community
  • 1
  • 1
John Muiruri
  • 26
  • 1
  • 1
  • 6
0

If you are getting an exit code, then your script is executed. There is a command that you are running inside of "Mail.sh", which is not succeccfully executed and returning a status code of 127.
There could be some paths that are explicitly set in your shell, but is not available to the script, when executed outside of the shell. Try this...

  • Check if you are able to run /xyz/downloads/Report/Mail.sh in a shell terminal. Fix the errors if you have any.
  • If there are no errors when you run this in a terminal, then try running the command using a shell in your java program. String[] commands = {"/bin/sh", "-c", scriptName,emailid,subject,body};
    (Check @John Muiruri's answer to get the complete output of your command. You can see where exactly your script is failing, if you add those lines of code)
Pradhan
  • 518
  • 4
  • 14