Execute a bash script via C#/.NET Core

With .NET Core now being a cross-platform framework, it’s very easy to invoke a Bash script from C# codes. It’s not a common practice, but in cases that are lack of a .NET library or REST/rpc API, being able to run a script out-of-process is valuable. So here is a nice extension method that I wrote and found it a joy to call.

public static class ShellHelper
public static Task<int> Bash(this string cmd, ILogger logger)
var source = new TaskCompletionSource<int>();
var escapedArgs = cmd.Replace("\"", "\\\"");
var process = new Process
StartInfo = new ProcessStartInfo
FileName = "bash",
Arguments = $"-c \"{escapedArgs}\"",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
EnableRaisingEvents = true
process.Exited += (sender, args) =>
if (process.ExitCode == 0)
source.SetException(new Exception($"Command `{cmd}` failed with exit code `{process.ExitCode}`"));
catch (Exception e)
logger.LogError(e, "Command {} failed", cmd);
return source.Task;
view raw bash_helper.cs hosted with ❤ by GitHub

To call the method, one can simply do, e.g.:

await $"scripts/00magic.sh --param {arg}".Bash(this.logger);
Execute a bash script via C#/.NET Core

One thought on “Execute a bash script via C#/.NET Core

  1. nice one. How can I call a .sh file located somewhere local to this service instead of hard coding a command? I want to run multiple commands and one of them takes input so I want to run it in non-interactive mode.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s