Created
November 4, 2018 19:16
-
-
Save GokuVegetaKrillin/d99c38ee9e8c0fc50af4073c51049ea3 to your computer and use it in GitHub Desktop.
Running shell (bash) commands
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Diagnostics; | |
| public static class ShellHelper | |
| { | |
| public static string Bash(this string cmd) | |
| { | |
| var escapedArgs = cmd.Replace("\"", "\\\""); | |
| var process = new Process() | |
| { | |
| StartInfo = new ProcessStartInfo | |
| { | |
| FileName = "/bin/bash", | |
| Arguments = $"-c \"{escapedArgs}\"", | |
| RedirectStandardOutput = true, | |
| UseShellExecute = false, | |
| CreateNoWindow = true, | |
| } | |
| }; | |
| process.Start(); | |
| string result = process.StandardOutput.ReadToEnd(); | |
| process.WaitForExit(); | |
| return result; | |
| } | |
| } | |
| // It’s an extension method, so after importing the namespace (if different), you can use it like this: | |
| // var output = "ps aux".Bash(); | |
| // output will contain the STDOUT of the result. Currently STDERR is not captured, but the above could easily be modified to do just that by changing the // // property RedirectStandardOutput and reading process.StandardError. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment