从Mono C#运行Bash命令

本文关键字:Bash 命令 运行 Mono | 更新日期: 2023-09-27 17:57:57

我正试图用这段代码创建一个目录,看看代码是否正在执行,但由于某种原因,它执行时没有错误,但从未创建目录。我的代码中有错误吗?

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();

从Mono C#运行Bash命令

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

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("/bin/bash", "-c '"echo 'Hello World!''"");

我的猜测是您的工作目录不是您期望的位置。

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

同样您的命令似乎是错误的,使用&&执行多个命令:

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

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

 proc.StartInfo.WorkingDirectory = "/home";