gpt4 book ai didi

c# - 从 Mono C# 运行 Bash 命令

转载 作者:行者123 更新时间:2023-11-30 19:09:46 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于c# - 从 Mono C# 运行 Bash 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23029218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com