首页 > 解决方案 > 使用 .NET Core 在 Linux 中通过“/bin/bash”执行 .sh(bash 脚本)文件

问题描述

操作系统:Linux 4.15.0-48-generic #51-Ubuntu
框架:.NET Core 4.6.27817.03

我在下面有以下sample.sh文件:

 #!/bin/bash
 netstat --tcp --listen --numeric-ports -p

以及执行此文件的以下函数:

string filePathExecute = "./Assets/SystemTests/sample.sh";
FileInfo fileInfo = new FileInfo(filePathExecute);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = true;
startInfo.FileName = "/bin/bash";
startInfo.Arguments = $"\"{fileInfo.FullName}\"";
Process process = Process.Start(startInfo);

但我得到以下输出:

xdg-open: unexpected argument '/home/{filePathHere}/Assets/SystemTests/sample.sh'
Try 'xdg-open --help' for more information.

如何让我的应用程序打开一个新的终端窗口并sample.sh在其中运行?

标签: c#linuxbash.net-core

解决方案


经过 10 分钟的试验,一个经典的发现解决方案发生了。不知道为什么,但在跟随标志之后,它开始工作:

startInfo.UseShellExecute = false;

在运行 powershell.ps1 文件时,我不会在 Windows 上执行此操作。此外,此方法还没有打开新窗口,在相同的窗口上运行,但现在它可以工作了。


推荐阅读