从Mono C#运行Bash命令

我试图使用此代码创建一个目录,以查看代码是否正在执行但由于某种原因它执行没有错误,但目录永远不会。 我的代码在某处有错误吗?

var startInfo = new var startinfo = new ProcessStartInfo(); startinfo.WorkingDirectory = "/home"; proc.StartInfo.FileName = "/bin/bash"; proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey"; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start (); Console.WriteLine ("Shell has been executed!"); Console.ReadLine(); 

这对我有用:

 Process.Start("/bin/bash", "-c \"echo 'Hello World!'\""); 

这对我来说效果最好,因为现在我不必担心转义引号等…

 using System; using System.Diagnostics; class HelloWorld { static void Main() { // lets say we want to run this command: // t=$(echo 'this is a test'); echo "$t" | grep -o 'is a' var output = ExecuteBashCommand("t=$(echo 'this is a test'); echo \"$t\" | grep -o 'is a'"); // output the result Console.WriteLine(output); } static string ExecuteBashCommand(string command) { // according to: https://stackoverflow.com/a/15262019/637142 // thans to this we will pass everything as one command command = command.Replace("\"","\"\""); var proc = new Process { StartInfo = new ProcessStartInfo { FileName = "/bin/bash", Arguments = "-c \""+ command + "\"", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; proc.Start(); proc.WaitForExit(); return proc.StandardOutput.ReadToEnd(); } } 

我的猜测是你的工作目录不是你想象的那样。

有关 Process.Start()工作目录的更多信息, 请参见此处

你的命令似乎也错了,用&&来执行多个命令:

  proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey"; 

第三,你错误地设置你的工作目录:

  proc.StartInfo.WorkingDirectory = "/home"; 
Interesting Posts