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.

15 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. Fogoros Andrei Nicolae

    Hi,
    Can you tell me, please, under which license the above code is placed?

Leave a Reply

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