Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exectute a Linux Shell command from ASP.NET Core 3 app

My question is literally, how do I execute a Shell command from my application. There is a similar Post, but that shows how to execute a script file and requires the path to that file.

var process = new Process()
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = command, // Path required here
            Arguments = args,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true,
        }
    };
process.Start();

Why I want to pass the command as a string?

Because I want to interpolate it. Otherwise, I would have to create a script, with some input parameters. Since I'm not that good with Shell, I prefer the easy way.

like image 352
Gicu Mironica Avatar asked Oct 23 '25 18:10

Gicu Mironica


1 Answers

Assume you want to run echo hello in bash, then

    Process process = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = "bash",
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false
        }
    };
    process.Start();
    await process.StandardInput.WriteLineAsync("echo hello");
    var output = await process.StandardOutput.ReadLineAsync();
    Console.WriteLine(output);
like image 159
Lex Li Avatar answered Oct 26 '25 07:10

Lex Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!