Home > database >  How to chain Linux commands in .net 5
How to chain Linux commands in .net 5

Time:09-24

is there any way to use .NET 5 Process class to use chain linux commands like I would to in a terminal?

$ cat /proc/meminfo | grep MemTotal

The command above would return the memory the system has, I can run cat with "/proc/meminfo" as an argument, but how could I do it all at once?

EDIT: Tried to set the filename to "/bin/bash" and to pass "cat /proc/meminfo | grep MemTotal" as arguments but it still doesn't work, throwing the error /usr/bin/cat: /usr/bin/cat: cannot execute binary file

EDIT 2: Found a solution, here's the code that works

        Process process = new Process();
        process.StartInfo.FileName = "/bin/sh";
        string cmd = "cat /proc/meminfo | grep MemTotal";
        process.StartInfo.Arguments = $"-c \"{cmd}\"";

        process.StartInfo.RedirectStandardOutput = true;
        process.Start();
        process.WaitForExit();
        Console.WriteLine(process.StandardOutput.ReadToEnd());

CodePudding user response:

Found the answer

        Process process = new Process();
        process.StartInfo.FileName = "/bin/sh";
        string cmd = "cat /proc/meminfo | grep MemTotal";
        process.StartInfo.Arguments = $"-c \"{cmd}\"";

        process.StartInfo.RedirectStandardOutput = true;
        process.Start();
        process.WaitForExit();
        Console.WriteLine(process.StandardOutput.ReadToEnd());
  • Related