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

MacOS下C#执行.sh脚本无报错但未运行问题求助

MacOS下C#运行.sh脚本无响应无错误的排查方案

1. 未读取重定向输出导致进程阻塞

你开启了RedirectStandardOutput和RedirectStandardError但没主动读取输出流,进程会因为输出缓冲区填满而挂起,既无法执行完成,也不会返回任何信息。

解决办法:
启动进程后必须读取输出和错误流,示例代码:

var startInfo = GetMacOSStartInfo("/path/to/your/script.sh");
using (var process = Process.Start(startInfo))
{
    string output = process.StandardOutput.ReadToEnd();
    string error = process.StandardError.ReadToEnd();
    process.WaitForExit();
    
    // 打印输出和错误,排查具体问题
    Console.WriteLine("输出内容:");
    Console.WriteLine(output);
    Console.WriteLine("错误信息:");
    Console.WriteLine(error);
}

2. 脚本工作目录不匹配

你的.sh脚本用了相对路径cmake ..,但C#默认以程序当前工作目录启动进程,不是脚本所在目录,这会导致cmake找不到上级目录的CMakeLists.txt,脚本执行失败但没错误提示。

解决办法:
在ProcessStartInfo中指定工作目录为脚本所在路径:

public static ProcessStartInfo GetMacOSStartInfo(string path)
{
    string fileName = "/bin/bash";
    string argument = path;
    string workingDir = Path.GetDirectoryName(path); // 获取脚本所在目录
    return new ProcessStartInfo
    {
        FileName = fileName,
        Arguments = argument,
        UseShellExecute = false,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        CreateNoWindow = true,
        WindowStyle = ProcessWindowStyle.Hidden,
        WorkingDirectory = workingDir // 添加工作目录设置
    };
}

3. 脚本路径含空格时参数解析错误

如果脚本路径包含空格,直接传path会被bash拆成多个参数,导致bash找不到正确的脚本文件。

解决办法:
把路径用双引号包裹,确保bash识别为单个参数:

string argument = $"\"{path}\"";

4. 脚本权限验证(可选)

虽然用bash script.sh运行不需要脚本有可执行权限,但如果权限异常也可能出问题。可以手动给脚本加可执行权限试试:

chmod +x /path/to/your/script.sh

5. 验证脚本本身是否正常

先排除脚本自身的问题:在终端切换到脚本所在目录,执行bash script.sh,看是否能正常运行。如果手动执行也失败,那问题出在脚本内容(比如cmake ..指向的目录没有CMakeLists.txt)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 04:52:16