2017-05-15 38 views
0

如何通過java代碼調用shell腳本? 我寫下了下面的代碼。 我得到的進程退出代碼爲127. 但似乎我的UNIX機器上的shell腳本從未被調用過。從java獲取錯誤

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(); 
} 
+0

是腳本可執行+ X? –

+0

是的,我已經給了chmod 777 – chandan

回答

0

從這個帖子在這裏127 Return code from $?

你得到的錯誤代碼,如果命令不在路徑中找到或文字沒有+ X模式。 你可以有下面的代碼打印出精確的輸出

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); 
      } 
0

如果您收到的退出代碼,那麼你的腳本執行。有一個命令在「Mail.sh」中運行,它不會被成功執行並返回狀態碼127.
可能有一些路徑在shell中顯式設置,但不可用於腳本,當在shell外執行時。如果你能在一個shell終端上運行/xyz/downloads/Report/Mail.sh 嘗試......

  • 檢查。如果有任何問題,請修正錯誤。
  • 如果在終端中運行此命令時沒有錯誤,則嘗試在java程序中使用shell運行該命令。 String[] commands = {"/bin/sh", "-c", scriptName,emailid,subject,body};
    (檢查@約翰Muiruri的答案讓你的命令的完整輸出,你可以清楚地看到你的腳本失敗,如果您添加的這些代碼行)