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.

4 thoughts on “Running shell (bash) commands in .NET Core C#

  1. krishna reddy

    I am unable to run the linux command using dotnet core., followed the same steps but could not actually see the output of it.,
    I am actually trying to run the commands to set the network configuration using c#.
    Please help me in solving this to setup network configuration using c#.,the following is the code .

    var args = string.Format(“ifconfig {0} {1} netmask {2} up”, networkType, ipAddress, subnet);

    Process process = new Process();
    ProcessStartInfo startInfo = new ProcessStartInfo
    {
    FileName = “/bin/bash”,
    Arguments = “-c \”{args}\””,
    RedirectStandardOutput = true,
    UseShellExecute = false,
    CreateNoWindow = true,
    };

    startInfo.ErrorDialog = false;

    startInfo.RedirectStandardError = true;
    startInfo.RedirectStandardInput = true;

  2. John

    I had to use the verbatim identifier on the strings to get the command to run: arguments.Replace(@”\”, @”/”)

Leave a Reply

Your email address will not be published. Required fields are marked *