我想使用C#来执行shell脚本。 基于类似的问题,我找到了一个看起来像这样的解决方案。
System.Diagnostics.Process.Start("/Applications/Utilities/Terminal.app","sunflow/sunflow.sh");
它当前打开终端,然后使用默认应用程序(在我的情况下为Xcode)打开shell文件。无法更改默认应用程序,因为需要为其他用户安装此应用程序。
理想情况下,该解决方案将允许shell文件的参数。
答案 0 :(得分:7)
我现在无法使用Mac进行测试,但以下代码适用于Linux并且可以在Mac上运行,因为Mono非常接近微软的核心.NET接口:
ProcessStartInfo startInfo = new ProcessStartInfo()
{
FileName = "foo/bar.sh",
Arguments = "arg1 arg2 arg3",
};
Process proc = new Process()
{
StartInfo = startInfo,
};
proc.Start();
关于我的环境的几点说明:
我在子目录foo中创建了一个文件bar.sh,其代码如下:
#!/bin/sh
for arg in $*
do
echo $arg
done
我在Test.cs中围绕上面的C#代码包装了Main
方法,并使用dmcs Test.cs
进行了编译,并使用mono Test.exe
执行。
答案 1 :(得分:0)
谢谢 Adam,这对我来说是一个很好的起点。但是,由于某种原因,当我尝试使用上述代码(根据我的需要更改)时,出现以下错误
System.ComponentModel.Win32Exception: Exec format error
请参阅下面给出上述错误的代码
ProcessStartInfo startInfo = new ProcessStartInfo()
{
FileName = "/Users/devpc/mytest.sh",
Arguments = string.Format("{0} {1} {2} {3} {4}", "testarg1", "testarg2", "testarg3", "testarg3", "testarg4"),
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
Process proc = new Process()
{
StartInfo = startInfo,
};
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string result = proc.StandardOutput.ReadLine();
//do something here
}
并花了一些时间在下面提出,它在我的情况下有效 - 以防万一有人遇到此错误,请尝试以下
工作解决方案:
var command = "sh";
var scriptFile = "/Users/devpc/mytest.sh";//Path to shell script file
var arguments = string.Format("{0} {1} {2} {3} {4}", "testarg1", "testarg2", "testarg3", "testarg3", "testarg4");
var processInfo = new ProcessStartInfo()
{
FileName = command,
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
Process process = Process.Start(processInfo); // Start that process.
while (!process.StandardOutput.EndOfStream)
{
string result = process.StandardOutput.ReadLine();
// do something here
}
process.WaitForExit();