Created
September 14, 2022 18:50
-
-
Save n8allan/88efdcbb1cd6d2c1e4aef72d3fc26674 to your computer and use it in GitHub Desktop.
C# async Bash function
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
public static Task<string> Bash(string cmd, int[] acceptableCodes = null) | |
{ | |
var source = new TaskCompletionSource<string>(); | |
var escapedArgs = cmd.Replace("\"", "\\\""); | |
var process = new Process | |
{ | |
StartInfo = new ProcessStartInfo | |
{ | |
FileName = "bash", | |
Arguments = $"-c \"{escapedArgs}\"", | |
RedirectStandardOutput = true, | |
RedirectStandardError = true, | |
UseShellExecute = false, | |
CreateNoWindow = true | |
}, | |
EnableRaisingEvents = true | |
}; | |
process.Exited += (sender, args) => | |
{ | |
var result = process.StandardOutput.ReadToEnd(); | |
var error = process.StandardError.ReadToEnd(); | |
if (process.ExitCode == 0 || (acceptableCodes != null && acceptableCodes.Contains(process.ExitCode))) | |
{ | |
source.SetResult(result); | |
} | |
else | |
{ | |
source.SetException(new Exception($"Command `{cmd}` failed with exit code `{process.ExitCode}`")); | |
} | |
process.Dispose(); | |
}; | |
try | |
{ | |
process.StartInfo.RedirectStandardOutput = true; | |
process.Start(); | |
} | |
catch (Exception e) | |
{ | |
source.SetException(e); | |
} | |
return source.Task; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment