.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,则抛出异常。

相关推荐
vortex51 小时前
探索 Shell:选择适合你的命令行利器 bash, zsh, fish, dash, sh...
linux·开发语言·bash·shell·dash
GalaxyPokemon1 小时前
LeetCode - 148. 排序链表
linux·算法·leetcode
懒羊羊大王呀2 小时前
Ubuntu20.04中 Redis 的安装和配置
linux·redis
杰哥技术分享2 小时前
在 CentOS 上安装 Docker 和 Docker Compose 并配置使用国内镜像源
linux·docker·centos
o0向阳而生0o2 小时前
63、.NET 异常处理
c#·.net·异常处理
知更鸟呆呆2 小时前
【Linux操作系统】基础开发工具(yum、vim、gcc/g++)
linux·运维·vim
xiangyong582 小时前
ubuntu系统文件误删(/lib/x86_64-linux-gnu/libc.so.6)修复方案 [成功解决]
linux·ubuntu·gnu
t198751283 小时前
Linux 上的 Tomcat 端口占用排查
linux·tomcat·firefox
小狗爱吃黄桃罐头3 小时前
正点原子[第三期]Arm(iMX6U)Linux移植学习笔记-12.1 Linux内核启动流程简介
linux·arm开发·学习
地衣君4 小时前
Ubuntu 配置使用 zsh + 插件配置 + oh-my-zsh 美化过程
linux·运维·ubuntu