查了很多关于Process的资料,大部分都是关于Win下如何实现,但是MacOS下面的实现方式非常少,部分需要借助AppleScript的语法进行实现

这里我们用startTerminal来判断是否需要启用Terminal

public static void Bash(this string cmd, string workingDirectory, bool startTerminal = false) {

    ProcessStartInfo startInfo = new ProcessStartInfo("/bin/bash") {
        WorkingDirectory = workingDirectory,
        UseShellExecute = false,
        RedirectStandardInput = true,
        RedirectStandardOutput = true
    };

    Process process = new Process {
        StartInfo = startInfo
    };

    process.Start();
    string code = "";
    if(startTerminal) {
        code = "osascript -e 'tell application \"Terminal\" to do script \"" +
               "" + cmd + "\" in selected tab of the front window'";
    } else {
        code = cmd;
    }

    process.StandardInput.WriteLine(code);
    process.StandardInput.WriteLine("exit");
    process.StandardInput.Flush();

    string line = process.StandardOutput.ReadLine();

    while(line != null) {
        UnityEngine.Debug.Log("line:" + line);
        line = process.StandardOutput.ReadLine();
    }
    process.WaitForExit();
}

实际使用

// 使用go服务,创建一个新的Terminal
string path = System.Environment.CurrentDirectory + "/../FileServer/";
            ("cd " + path + " && go run FileServer.go").Bash(path, true);
// 不创建新的Terminal,执行sh文件
"bash ./protoc.sh".Bash(System.Environment.CurrentDirectory);

What doesn’t kill you makes you stronger.