Search code examples
c#linuxbashshellcygwin

How to execute a linux shell script from a C# application?


I have a linux shell script which I can execute manually with CygWin terminal in windows.

sh E://Work/sync.sh E://Work/Voice/Temp

But I'm having some difficulty when I'm trying to run the shell script in my C# application with the same argument.

string command = "E://Work/sync.sh E://Work/Voice/Temp";
ProcessStartInfo psi = new ProcessStartInfo(@"C:\cygwin64\bin\bash.exe", command);
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
Process p = Process.Start(psi);
Console.WriteLine(p.StandardError.ReadToEnd());
Console.WriteLine(p.StandardOutput.ReadToEnd());

It's giving me error:

E://Work/sync.sh: line 47: rm: command not found
E://Work/sync.sh: line 48: mkdir: command not found
E://Work/sync.sh: line 50: ls: command not found
E://Work/sync.sh: line 59: ls: command not found
E://Work/sync.sh: line 60: rmdir: command not found

Then I tried a different approach.

ProcessStartInfo psi = new ProcessStartInfo(@"C:\cygwin64\bin\bash.exe");
psi.Arguments = "--login -c sh E://Work/sync.sh  E://Work/Voice/Temp";
Process p = Process.Start(psi);

This initiates a CygWin command prompt like this: enter image description here

Then if I enter my command manually it works. E://Work/sync.sh E://Work/Voice/Temp

How can I execute the script automatically from my application without any manual input?


Solution

  • After doing some google search, I found a way to do this. All I had to do is change "--login -c" to "--login -i"

    ProcessStartInfo psi = new ProcessStartInfo(@"C:\cygwin64\bin\bash.exe");
    psi.Arguments = "--login -i E://Work/sync.sh  E://Work/Voice/Temp";
    Process p = Process.Start(psi);