Skip to content

Instantly share code, notes, and snippets.

@brenocogu
Created May 6, 2025 17:02
Show Gist options
  • Save brenocogu/f743688878421180b3ead24083fb9f32 to your computer and use it in GitHub Desktop.
Save brenocogu/f743688878421180b3ead24083fb9f32 to your computer and use it in GitHub Desktop.
ShellHelper - use it to easily query `sh` commands on `C#`
using System;
using System.Threading.Tasks;
using System.Diagnostics;
using Debug = UnityEngine.Debug;
/// <summary>
/// Easily invoke shell commands using this class. CI Friendly. Asynchronous
/// <example>await "pod install".Bash();</example>
/// </summary>
public static class ShellHelper
{
public static Task<int> Bash (this string cmd)
{
TaskCompletionSource<int> source = new TaskCompletionSource<int>();
string escapedArgs = cmd.Replace("\"", "\\\"");
Process 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) =>
{
Debug.Log(process.StandardError.ReadToEnd());
Debug.Log(process.StandardOutput.ReadToEnd());
if (process.ExitCode == 0)
source.SetResult(0);
else
source.SetException(new Exception($"Command `{cmd}` failed with exit code `{process.ExitCode}`"));
process.Dispose();
};
try
{
process.Start();
}
catch (Exception e)
{
Debug.LogError($"Command {cmd} failed {e.Message} ");
source.SetException(e);
}
return source.Task;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment