Calling Bash Commands from .Net Core

Publish date: May 11, 2019
Tags: .net core, c#, bash, terminal

Using System Diagnostics

To spawn a process in a .NET application is not a hard task, as you ca n imagine. In Windows environment you`d just call:

using System.Diagnostics;

...

Process.Start("nameOfTheProcess");

..and take it from there.

Now guess what, it is completely the same in .NET Core, on any platform!

Linux/Mac

The same thing will apply in Unix environment, however you won’t be able to just use the name of the process as we did before. If you`ll do something like:

using System;
using System.Diagnostics;

namespace spawn
{
    class Program
    {
        static void Main(string[] args)
        {
            Process.Start("touch a.js");
        }
    }
}

This should create a file named ‘a.js’. And when you run it in the terminal (bash), it will do exactly this. You can verify that

dotnet run

It’s going to output, that a Win32Exception because we`ve mixed the command with its argument. If we want to pass any arguments, we will need to use a different method overload, one which takes command + arguments:

using System;
using System.Diagnostics;

namespace spawn
{
    class Program
    {
        static void Main(string[] args)
        {
            Process.Start("touch", "a.js");
        }
    }
}

This will do.

Don`t let the process hang

Let’s create a js file, which outputs ‘hi from js’.

echo "console.log('hi from js');" > hi.js

Now lets call node from our .NET Core app, and ask it to run this js file and output the text for us:

using System;
using System.Diagnostics;

namespace spawn
{
    class Program
    {
        static void Main(string[] args)
        {
            Process.Start("node", "hi.js");
        }
    }
}

dotnet run

All good, but there is one tiny quirk, is your terminal still busy? Just hit CTRL+C, and go ahead and update the code, so that our console app waits for the underlying process to exit:

using System;
using System.Diagnostics;

namespace spawn
{
    class Program
    {
        static void Main(string[] args)
        {
            var myProcess = Process.Start("node", "hi.js");
            myProcess.WaitForExit();
        }
    }
}