There are many reasons why it could be handy to run a bash script from a C# application. In 2014, before I changed to a Mac as my daily driver, I had to do something similar for Windows. I had to run some a script when the application started. Bash was, of course, not an option. So I ran a Visual Basic script. You can read more about that here if it is of any interest.
How to run a bash script from a C# application? Let us take a look at how to do it. In this example I will use the .net5 framework. You need to add the System.Diagnostic namespace to get access to the Process class. The Process gives us the ability to run external scripts outside of our application. There are many ways you can trigger them. On start, on exit or any other condition you can think of.
C# Bash Script Step by Step
First we add the namespace.
using System.Diagnostics;
Then we create a instance of the Process class.
Process extScript = new Process();
The only information we have to give it is the name of the script we want to launch. Here we assume it is in the same directory.
extScript.StartInfo.FileName = @"script.sh";
It is time to execute the script. We do that using the start() method.
extScript.Start();
That is everything you need to run a script or a executable from your application. In case the script you are running a processing something that takes a few seconds, and you want to wait for it to finish. We use the WaitForExit() method.
extScript.WaitForExit();
Let us have a look at a complete example on how it works in most version of .NET, including .NET5.
using System;
using System.Diagnostics;
namespace Script
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("External Script Test");
Process extScript = new Process();
extScript.StartInfo.FileName = @"script.sh";
extScript.Start();
extScript.WaitForExit();
}
}
}
Remember the script.sh needs to be executable.
For .NET6 it will look like this.
using System.Diagnostics;
Console.WriteLine("External Script Test");
Process extScript = new Process();
extScript.StartInfo.FileName = @"script.sh";
extScript.Start();
extScript.WaitForExit();
If you want to know more about the Diagnostic namespace, or the Process class. Click the links where I have highlighted them here.
So this is how you run a bash script from C# in Linux or macOS.