从C#运行Bash命令

时间:2015-02-12 20:27:22

标签: c# git bash shell

我试图弄清楚如何在IIS 7 / .Net 4.5上运行C#运行bash命令。

我一直在网上搜索,很多答案都假设您已经安装了某些东西。

我已经安装了Git Bash和Git Giu Git 1.9.4.msysgit.2。我正在寻找一些帮助,我还需要安装什么来运行最简单的bash命令。以及如何运行它。

我查看了bash pipes - I am trying to call script from c#这样的帖子,但使用了cygwin。没有它我可以做同样的事情,如果是这样,我该怎么做呢?

目标

如果我上面提到的问题没有意义,或者似乎问了不同的问题,那么这就是我的最终目标。我正在尝试编写自己的服务器端git hook。当开发人员pushes提交我们的GitHub仓库时,我希望GitHub调用我们的回调URL。我希望我的回调网址运行git pull命令,用刚刚推送的内容更新我们的staging服务器。

我根据我在GitHub - setup auto deployment with remote server提出的上一个问题得出了这个问题。基于那里的答案,我试图运行一个简单的命令,或者硬编码命令,或者将它放在脚本中并运行它,例如:cd $REPO_DIR && git pull origin $branch_name

我知道Jenkins和其他软件,但我想自己执行这些命令而不是安装其他软件。

如果需要进一步的信息,请随时询问。

更新1

基于以下几个答案,我提出了以下内容

using System.Diagnostics;

Process process = new Process();

ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.FileName = @"C:\Program Files (x86)\Git\bin\bash.exe";
processStartInfo.WorkingDirectory = @"C:\myrepo\mysite";
processStartInfo.Arguments = "git status";
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.UseShellExecute = false;

process.StartInfo = processStartInfo;
process.Start();

String error = process.StandardError.ReadToEnd();
String output = process.StandardOutput.ReadToEnd();

ViewBag.Error = error;
ViewBag.Ouput = output;

根据上面的代码,我得到了"C:/Program Files (x86)/Git/bin/bash.exe": git: No such file or directory。我知道exe就在那里。我做错了什么?

更新2

根据@SurgeonofDeath评论,我关注了这篇文章http://blog.countableset.ch/2012/06/07/adding-git-to-windows-7-path/,并将Git的路径添加到我的环境变量中。但是我仍然遇到同样的问题。有什么想法吗?

感谢。

3 个答案:

答案 0 :(得分:1)

不要调用bash.exe,只需调用git并将状态作为参数传递:

processStartInfo.FileName = "git";
processStartInfo.Arguments = "status";

答案 1 :(得分:0)

也许我误解了你的问题但是execve呢? 这是它的手册页的摘录。

  

NAME

   execve - execute program
     

概要

   #include <unistd.h>

   int execve(const char *filename, char *const argv[],
              char *const envp[]);
     

说明

   execve() executes the program pointed to by filename.  filename must > be
   either a binary executable, or a script starting with  a  line  of  > the
   form:

       #! interpreter [optional-arg]

答案 2 :(得分:0)

检查您的PATH环境变量并更新它

  

C:/ Program Files(x86)/Git/bin/bash.exe“:git:没有这样的文件或目录

表示 bash 找不到 git

<强> 1。检查bash中的PATH环境变量(这与应该保持不同于Windows)

调整此

processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

使终端可见。

在终端中,您将使用Process.Start()

创建

类型:

echo ${PATH}

<强> 2。更新路径

  • 您可以更新Windows的全局路径(需要重新启动)
  • 您可以更新Windows的用户路径(应该需要注销,但我不确定)。
  • 您只需在启动System.Environment.SetEnvironmentVariable
  • 之前使用Process将路径设置为您喜欢的内容

附加说明:

如果你喜欢我的几个版本的bash,命令解释器,git等,如果你试图连接所有的路径并希望找到理想的顺序,它可能会非常麻烦。你可以看到你心爱的命令的一些奇怪的行为,直到你意识到它不是你打算运行的那个...想想FIND.exe ......我甚至没有想到用户友好的用于编辑环境变量的窗口界面......