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.

9 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(@”\”, @”/”)

  3. Goran

    I know this will come of as dumb question, but I don’t have much experience in linux.
    What is the use of “-c” in arguments?

  4. Gennady Verdel

    I was unable to run your code. Looks like for some reason my system does not recognize /bin/bash when run by ProcessStartInfo

  5. Emre

    Very useful helper, it helped me along my school project with using Raspbian. I had to get information from exiftool using bash. This helped me a lot.

  6. financialmarketingnews.com

    I am the head web developer ffor tһe Е-mail Extractor annd Search Engine Scraper
    ƅy Creative Bear Tech. In ɑ nutshell, tһіѕ search engine scraper can scrape mist оf the search engines, including
    Google, Bing, AOL, Yandex and even social media platforms lіke Facebook,Instagram,
    Twitter, LinkedIn, Yelllow Рages, Google Maps аnd sо mucһ more.
    I think it wilⅼ be a lot easier if уou gօ over the full tutorial
    аt https://blockchainlifemag.com/2019/05/21/guide-email-extractor-and-search-engine-scraper-by-creative-bear-tech. Tһe software application іs not officfial уet, Ьut whenever it іs, it ᴡill
    bbe гeadily аvailable ⲟn https://creativebeartech.com

    We are presently bwta testing tһe software and tryiong
    to find betа tester ɑnd software reviewers. Уou will Ьe giνen the fսll
    licence key foor the software and cann even scrape Ᏼ2B contact іnformation fߋr your own sector.
    Ιf interested, pleaase gіve me ɑ shout on Facebook https://www.facebook.com/Creative-Bear-Tech-2284249764963533/or ϳust reply tօ thiѕ thread.

Leave a Reply

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