Monthly Archives: June 2017

Running shell (bash) commands in .NET Core C#

In a lot of languages and platforms, you can easily execute shell or bash commands – like using back tick for example in PHP:
[php]
`echo hello`;
[/php]

In the .NET Core world, it’s a little bit more involved – so I wrote a helper class:

[csharp]
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;
}
}

[/csharp]

It’s an extension method, so after importing the namespace (if different), you can use it like this:

[csharp]
var output = "ps aux".Bash();
[/csharp]

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.