You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows环境下用Java执行Shell脚本遇退出码127问题求助

Windows下Java执行Shell脚本退出码127的解决方案

问题背景

在Windows机器上通过Java执行Shell脚本,执行后脚本退出码为127而非预期的0,尝试使用git相关方法仍未解决。

所用代码及脚本

Java代码

public static void main(String[] args) throws IOException, InterruptedException {
    String abc;
    String abc1;

    Process proc = Runtime.getRuntime().exec("bash.exe C:\\Users\\abc\\Downloads\\test.sh");
    proc.waitFor();
    System.out.println(proc.exitValue());

    InputStream st1 = proc.getInputStream();
    BufferedReader red1 = new BufferedReader(new InputStreamReader(st1));
    while ((abc = red1.readLine()) != null) {
        System.out.println("Stdout1: " + abc);
        if (abc != null) {
            abc1 = abc;
        }
    }
}

Shell脚本

#!/bin/bash
echo "hi"

解决方案

  • 指定bash.exe的绝对路径:Windows环境下bash.exe通常随Git安装,默认路径为C:\Program Files\Git\bin\bash.exe,直接写bash.exe可能因系统PATH未包含该路径导致找不到命令,修改执行命令为绝对路径形式:

    Process proc = Runtime.getRuntime().exec(new String[]{
        "C:\\Program Files\\Git\\bin\\bash.exe", 
        "C:\\Users\\abc\\Downloads\\test.sh"
    });
    

    (注意使用字符串数组传递参数,避免路径含空格时出现解析错误)

  • 读取错误输出排查问题:退出码127通常对应"命令未找到"类错误,原代码未读取进程的错误输出,无法定位具体问题。添加错误流读取逻辑:

    InputStream errStream = proc.getErrorStream();
    BufferedReader errReader = new BufferedReader(new InputStreamReader(errStream));
    String errLine;
    while ((errLine = errReader.readLine()) != null) {
        System.out.println("Stderr: " + errLine);
    }
    
  • 检查脚本权限及格式:确保Shell脚本的换行符为LF(Unix格式),Windows下默认是CRLF,可能导致bash解析错误;同时在Git bash中执行chmod +x test.sh,赋予脚本可执行权限。

内容的提问来源于stack exchange,提问作者user2315104

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 20:52:29