从Mono C#运行Bash命令

6

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

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

1
工作目录是什么? - thumbmunkeys
我的解决方案存储在一个名为“项目”的文件夹中,如果这是你的意思的话,它保存在一个拇指驱动器上。 - Brandon Williams
我假设您最终真正想要做的事情与创建目录不同。否则,使用Directory.CreateDirectory(string)似乎比通过shell更好。 - KevinS
桌面目录是否存在于/home目录下?如果是,为什么不将WorkingDirectory设置为“/home/Desktop”,然后只执行mkdir命令呢?我觉得这就是XY问题:http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem - KevinS
我想执行保存在我的桌面上的一个shell脚本。 - Brandon Williams
请使用绝对路径来指定“桌面”。 - knocte
3个回答

17

这对我来说是最好的选择,因为现在我不必担心转义引号等问题...

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://dev59.com/Pmsz5IYBdhLWcg3wn5fa#15262019
        // 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();
    }
}

谢谢,提供一个已经包含返回输出的示例对我帮助很大! - friday
1
我发现我需要使用 command = command.Replace("\"", "\\\""); 来正确处理转义引号。除此之外,这是一个非常有帮助的答案。谢谢你,亲切的人类。 - McHobbes

7
这对我有效:
Process.Start("/bin/bash", "-c \"echo 'Hello World!'\"");

1
我猜测你的工作目录不在你期望的位置。
请参考这里了解Process.Start()的工作目录更多信息。
另外,你的命令似乎有误,请使用&&来执行多个命令:
  proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey";

第三,你设置了错误的工作目录:
 proc.StartInfo.WorkingDirectory = "/home";

你是否知道执行这个命令的其他替代方法? - Brandon Williams
由于某些原因仍然存在问题。我会将我现在使用的代码发布为更新。 - Brandon Williams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接