Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Trying to run `bash -c ""` command with Process.Start/ShellExecute
// works in LinqPad
void Main()
{
ExecuteCommandLine("wt"); // works - this is resolved
ExecuteCommandLine("bash"); // The system cannot find the file specified
// actual command line I'm trying to fire
ExecuteCommandLine("bash -c \"cd /mnt/c/projects/Test/jekyll/help; bundle exec jekyll serve\"");
}
public void ExecuteCommandLine(string fullCommandLine,
string workingFolder = null,
int waitForExitMs = 0,
string verb = "OPEN",
ProcessWindowStyle windowStyle = ProcessWindowStyle.Normal)
{
string executable = fullCommandLine;
string args = null;
if (executable.StartsWith("\""))
{
int at = executable.IndexOf("\" ");
if (at > 0)
{
args = executable.Substring(at+1).Trim();
executable = executable.Substring(0, at);
}
}
else
{
int at = executable.IndexOf(" ");
if (at > 0)
{
if (executable.Length > at +1)
args = executable.Substring(at + 1).Trim();
executable = executable.Substring(0, at);
}
}
// this also doesn't work
// ShellExecute(IntPtr.Zero,verb,executable,args,workingFolder,(int) windowStyle);
var pi = new ProcessStartInfo();
pi.UseShellExecute = true;
pi.Verb = verb;
pi.WindowStyle = windowStyle;
pi.FileName = executable;
pi.WorkingDirectory = workingFolder;
pi.Arguments = args;
using (var p = Process.Start(pi))
{
if (waitForExitMs > 0)
{
if (!p.WaitForExit(waitForExitMs))
throw new TimeoutException("Process failed to complete in time.");
}
}
}
[DllImport("Shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment