Skip to content

Instantly share code, notes, and snippets.

@GokuVegetaKrillin
Created November 4, 2018 19:16
Show Gist options
  • Select an option

  • Save GokuVegetaKrillin/d99c38ee9e8c0fc50af4073c51049ea3 to your computer and use it in GitHub Desktop.

Select an option

Save GokuVegetaKrillin/d99c38ee9e8c0fc50af4073c51049ea3 to your computer and use it in GitHub Desktop.
Running shell (bash) commands
using System;
using System.Diagnostics;
public static class ShellHelper
{
public static string Bash(this string cmd)
{
var escapedArgs = cmd.Replace("\"", "\\\"");
var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = $"-c \"{escapedArgs}\"",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
}
};
process.Start();
string result = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return result;
}
}
// It’s an extension method, so after importing the namespace (if different), you can use it like this:
// var output = "ps aux".Bash();
// output will contain the STDOUT of the result. Currently STDERR is not captured, but the above could easily be modified to do just that by changing the // // property RedirectStandardOutput and reading process.StandardError.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment