简体   繁体   English

如何从 C# 应用程序执行 linux shell 脚本?

[英]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.我有一个 linux shell 脚本,我可以在 windows 中使用 CygWin 终端手动执行它。

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.但是,当我尝试使用相同的参数在 C# 应用程序中运行 shell 脚本时遇到了一些困难。

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:这将启动 CygWin 命令提示符,如下所示: 在此处输入图片说明

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?如何在没有任何手动输入的情况下从我的应用程序自动执行脚本?

After doing some google search, I found a way to do this.在做了一些谷歌搜索之后,我找到了一种方法来做到这一点。 All I had to do is change "--login -c" to "--login -i"我所要做的就是将"--login -c"更改为"--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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM