当前位置: 首页 > news >正文

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

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

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/bashArguments = $"-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.使用

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

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 无线领夹麦克风哪个牌子好,口碑最好的麦克风品牌,领夹麦推荐
  • 什么是数据资源?
  • ImportError: DLL load failed while importing _ssl: 找不到指定的模块的解决方法
  • .NET/C#⾯试题汇总系列:集合、异常、泛型、LINQ、委托、EF!(完整版)
  • 大模型从失败中学习 —— 微调大模型以提升Agent性能
  • 【贪心算法】贪心算法
  • 油耳用什么掏耳朵比较好?可视挖耳勺推荐平价
  • 【linux】 cd命令
  • DMA与AXI DMA ip
  • 【干货分享】Ftrans安全数据交换系统 搭建跨网数据传输通道
  • 工业大模型市场图谱:53个工业大模型全面梳理
  • CSS 笔记 1
  • 利用apache-pdfbox库修改pdf文件模板,进行信息替换
  • 【C++高阶】解锁C++的深层魅力——探索特殊类的奥秘
  • JVM面试真题总结(八)
  • 【391天】每日项目总结系列128(2018.03.03)
  • 【前端学习】-粗谈选择器
  • el-input获取焦点 input输入框为空时高亮 el-input值非法时
  • golang中接口赋值与方法集
  • Java多态
  • Python - 闭包Closure
  • Python 基础起步 (十) 什么叫函数?
  • RxJS: 简单入门
  • socket.io+express实现聊天室的思考(三)
  • vue 配置sass、scss全局变量
  • Vue 重置组件到初始状态
  • Vue2.x学习三:事件处理生命周期钩子
  • 构建工具 - 收藏集 - 掘金
  • 记一次和乔布斯合作最难忘的经历
  • 技术:超级实用的电脑小技巧
  • 讲清楚之javascript作用域
  • 快速构建spring-cloud+sleuth+rabbit+ zipkin+es+kibana+grafana日志跟踪平台
  • 利用DataURL技术在网页上显示图片
  • 使用parted解决大于2T的磁盘分区
  • 微服务核心架构梳理
  • 学习HTTP相关知识笔记
  • MPAndroidChart 教程:Y轴 YAxis
  • $Django python中使用redis, django中使用(封装了),redis开启事务(管道)
  • (07)Hive——窗口函数详解
  • (iPhone/iPad开发)在UIWebView中自定义菜单栏
  • (Redis使用系列) SpringBoot中Redis的RedisConfig 二
  • (学习日记)2024.03.25:UCOSIII第二十二节:系统启动流程详解
  • (转)Linux NTP配置详解 (Network Time Protocol)
  • .gitattributes 文件
  • .Net - 类的介绍
  • .Net Core 微服务之Consul(三)-KV存储分布式锁
  • .NET Core中的去虚
  • .NET delegate 委托 、 Event 事件,接口回调
  • .net 反编译_.net反编译的相关问题
  • .NET/C# 判断某个类是否是泛型类型或泛型接口的子类型
  • .net6+aspose.words导出word并转pdf
  • .net操作Excel出错解决
  • .Net下使用 Geb.Video.FFMPEG 操作视频文件
  • ??Nginx实现会话保持_Nginx会话保持与Redis的结合_Nginx实现四层负载均衡
  • @Conditional注解详解