Skip to content

Instantly share code, notes, and snippets.

@n8allan
Created September 14, 2022 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n8allan/88efdcbb1cd6d2c1e4aef72d3fc26674 to your computer and use it in GitHub Desktop.
Save n8allan/88efdcbb1cd6d2c1e4aef72d3fc26674 to your computer and use it in GitHub Desktop.
C# async Bash function
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