/// <summary> /// Run a shell command on the provided platform and retrieve the data returned by it. /// </summary> /// <param name="platform">The platform to run this shell command on.</param> /// <param name="command">The command to run.</param> /// <returns>Returns a string containing the output of the command.</returns> private string GetShellOutput(UnixPlatforms platform, string command) { try { // Set up our process to execute. var process = GetShellProcess(platform, $"-c \"{command}\"", true); // Stat the process and begin reading our data and error! process.Start(); process.WaitForExit(100); // Did we succeed? if (process.ExitCode == 0) { var output = process.StandardOutput.ReadToEnd(); return(output); } else { var error = process.StandardError.ReadToEnd(); return(error); } } catch (Exception e) { return(e.Message); } }
/// <summary> /// Create a new <see cref="Process"/> containing the shell command provided. /// </summary> /// <param name="platform">The platform to run this shell command on.</param> /// <param name="command">The command to run.</param> /// <param name="readable">Should the output of the command be readable?</param> /// <returns>Returns a process containing the shell command provided for execution.</returns> private Process GetShellProcess(UnixPlatforms platform, string command, bool readable) { var execFile = string.Empty; switch (platform) { case UnixPlatforms.Linux: execFile = "bash"; break; case UnixPlatforms.MacOSX: execFile = "zsh"; break; default: throw new NotImplementedException(); } return(new Process() { StartInfo = new ProcessStartInfo() { FileName = execFile, Arguments = command, RedirectStandardOutput = readable, RedirectStandardError = readable, UseShellExecute = false } }); }
/// <summary> /// Run a shell command on the provided platform. /// </summary> /// <param name="platform">The Platform to run this shell command on.</param> /// <param name="command">The command to run.</param> /// <param name="waitForExit">Should this application wait for the command to exit?</param> private void RunShell(UnixPlatforms platform, string command, bool waitForExit = false) { // Set up our process to execute. var process = GetShellProcess(platform, $"-c \"{command}\"", false); // Stat the process and begin reading our data and error! process.Start(); }