.Net 执行Linux下多行shell命令方法

1.编写 执行给定的多行 shell 命令 方法

csharp 复制代码
public class ShellCommandExecutor
{
    /// <summary>
    /// 执行给定的多行 shell 命令
    /// </summary>
    /// <param name="commands">多行 shell 命令</param>
    public void ExecuteMultiLineShellCommands(string commands)
    {
        // 确保所有换行符都是 LF (\n)
        string normalizedCommands = NormalizeNewlines(commands);

        var processInfo = new ProcessStartInfo
        {
            FileName = "/bin/bash", // 在 Linux 上使用 /bin/bash
            Arguments = $"-c \"{normalizedCommands}\"", // 使用 -c 参数执行命令
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true
        };

        using (var process = new Process())
        {
            process.StartInfo = processInfo;
            process.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data);
            process.ErrorDataReceived += (sender, e) => Console.Error.WriteLine(e.Data);

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.WaitForExit();

            if (process.ExitCode != 0)
            {
                throw new ApplicationException($"Shell command failed with exit code {process.ExitCode}");
            }
        }
    }

    /// <summary>
    /// 规范化换行符为 LF (\n)
    /// </summary>
    /// <param name="input">原始命令字符串</param>
    /// <returns>规范化后的命令字符串</returns>
    private string NormalizeNewlines(string input)
    {
        return input.Replace("\r\n", "\n").Replace("\r", "\n");
    }
}

2.使用

csharp 复制代码
class Program
{
    static void Main(string[] args)
    {
        var executor = new ShellCommandExecutor();
        try
        {
            // 定义多行 shell 命令
            string commands = @"
                echo 'First command output'
                echo 'Second command output'
            ";

            executor.ExecuteMultiLineShellCommands(commands);
            Console.WriteLine("Shell commands executed successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error executing shell commands: {ex.Message}");
        }
    }
}

3.解释

规范化换行符:

使用 NormalizeNewlines 方法将所有换行符替换为 LF(\n)。

这样可以确保在 Linux 系统上执行时不会出现问题。

执行 Shell 命令:

使用 ProcessStartInfo 配置进程启动信息。

设置 FileName 为 /bin/bash。

设置 Arguments 为执行命令所需的参数,使用 -c 参数来执行命令。

设置 UseShellExecute 为 false,以便更好地控制进程。

设置 RedirectStandardOutput 和 RedirectStandardError 为 true,以便捕获输出和错误信息。

使用事件处理程序 OutputDataReceived 和 ErrorDataReceived 来处理标准输出和错误输出。

异常处理:

如果进程退出码不为 0,则抛出异常。

相关推荐
玩泥巴的8 分钟前
.NET驾驭Word之力:基于规则自动生成及排版Word文档
c#·word·.net·com互操作
one year.13 分钟前
Linux:库制作与原理
linux·运维·服务器
陈苏同学13 分钟前
Win11安装 Ubuntu 22.04 子系统 - WSL2 - 安装完迁移到其它盘
linux·运维·ubuntu
专注VB编程开发20年25 分钟前
VB.NET多线程排序算法实现:LINQ与正则表达式方法
排序算法·.net·linq
蓝色土耳其love1 小时前
centos 7.9 安装单机版k8s
linux·运维·服务器·kubernetes·centos
小贾要学习1 小时前
如何在Linux操作系统环境下使用git命令提交文件到远程仓库
linux·运维·git
森G1 小时前
2二、u-boot移植
linux·arm开发
uxiang_blog1 小时前
C++进阶:重载类型转换
linux·开发语言·c++
洛克大航海1 小时前
CentOS8无法使用sudo提权
linux·centos·无法使用 sudo 提权
郝学胜-神的一滴2 小时前
使用Linux系统函数递归遍历指定目录
linux·运维·服务器·开发语言·c++·软件工程