【问题标题】:Run Bash Commands from Mono C#从 Mono C# 运行 Bash 命令
【发布时间】:2014-05-26 14:10:20
【问题描述】:

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

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

【问题讨论】:

  • 工作目录是什么?
  • 我假设您最终确实在尝试做其他事情(而不是创建目录)。否则,Directory.CreateDirectory(string) 似乎是比通过 shell 更好的选择。
  • /home 目录下是否存在桌面?如果是这样,您为什么不将 WorkingDirectory 设置为“/home/Desktop”并只执行 mkdir 命令?我觉得这是XY问题:meta.stackexchange.com/questions/66377/what-is-the-xy-problem
  • 我想执行一个保存在我桌面上的 shell 脚本。

标签: c# bash shell ubuntu mono


【解决方案1】:

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

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

【讨论】:

  • 谢谢,提供已经包含回传输出的示例对我有很大帮助!
  • 我发现我需要使用command = command.Replace("\"", "\\\""); 才能使转义引号正常工作。不过,除此之外,这是一个非常有用的答案。谢谢好心人。
【解决方案2】:

这对我有用:

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

【讨论】:

    【解决方案3】:

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

    See here了解更多Process.Start()工作目录的信息

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

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

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

     proc.StartInfo.WorkingDirectory = "/home";
    

    【讨论】:

    • 您是否知道执行此命令的另一种方法?
    • 由于某种原因仍有问题。我将发布我现在使用的代码作为更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    相关资源
    最近更新 更多