从 Mono C# 运行 Bash 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23029218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run Bash Commands from Mono C#
提问by Brandon Williams
I am trying to make a directory using this code to see if the code is executing but for some reason it executes with no error but the directory is never made. Is there and error in my code somewhere?
我正在尝试使用此代码创建一个目录,以查看代码是否正在执行,但由于某种原因,它执行时没有错误,但从未创建过该目录。我的代码中是否有错误?
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();
回答by Tono Nam
This works best for me because now I do not have to worry about escaping quotes etc...
这对我来说最有效,因为现在我不必担心转义引号等......
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();
}
}
回答by Alex Erygin
This works for me:
这对我有用:
Process.Start("/bin/bash", "-c \"echo 'Hello World!'\"");
回答by thumbmunkeys
My guess is that your working directory is not where you expect it to be.
我的猜测是您的工作目录不是您期望的位置。
See herefor more information on the working directory of Process.Start()
有关工作目录的更多信息,请参见此处Process.Start()
also your command seems wrong, use &&
to execute multiple commands:
您的命令也似乎错误,用于&&
执行多个命令:
proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey";
Thirdly you are setting your working directory wrongly:
第三,您错误地设置了工作目录:
proc.StartInfo.WorkingDirectory = "/home";