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:

`echo hello`;

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

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.