You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中向Bash发送含嵌套引号的命令?

问题

Bash环境

在SSH终端直接使用Bash时,以下命令可正常执行:

/bin/bash -c 'var="Hello World!"; echo "$var"'

输出结果为:

Hello World!

C#环境

使用以下示例代码执行时会报错:

using System.Diagnostics;

string command = "-c 'var=\"Hello World!\"; echo \"$var\"'";
Console.WriteLine("Command is: " + command);
string response = SendCommand(command);
Console.WriteLine("Response: " + response);

string SendCommand(string command)
{
    string processResponse = string.Empty;

    try
    {
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = "/bin/bash",
            Arguments = command,
            UseShellExecute = false,
            RedirectStandardError = true,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            CreateNoWindow = true,
        };

        Process shellProcess = new Process()
        {
            StartInfo = startInfo,
        };

        shellProcess.Start();
        StreamReader outputStreamReader = shellProcess.StandardOutput;
        StreamReader errorStreamReader = shellProcess.StandardError;

        string output = outputStreamReader.ReadToEnd();
        string error = errorStreamReader.ReadToEnd();
        if (output != string.Empty)
        {
            Console.WriteLine("Process Output Message: {0} ", output);
            processResponse = output;
        }

        shellProcess.WaitForExit(100);
        if (shellProcess.ExitCode != 0)
        {
            if (error != string.Empty)
            {
                processResponse = error;
                Console.WriteLine("Process Error Message: {0} for command {1}.", error, command);
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error to Send Process Command: " + ex.Message);
    }

    return processResponse;
}

报错信息:

Command is: -c 'var="Hello World!"; echo "$var"'

Error to Send Process Command: Input string was not in a correct format.

Response: echo: -c: line 1: unexpected EOF while looking for matching `''

echo: -c: line 2: syntax error: unexpected end of file

双引号嵌套双引号

在Bash中执行以下命令:

/bin/bash -c "var=\"Hello World! \"; echo \"\$var\""

输出结果为:

Hello World!

修改C#中的命令字符串为:

string command = "-c \"var=\\\"Hello World\\!\\\"; echo \\\"$var\\\"\"";

该方式可正常执行!但单引号包裹的方式在C#中报错的现象不符合预期。

注:Bash与C#中该命令的语法差异在于,SSH终端中$需加反斜杠转义,而C#中无需发送\\转义符。因双引号内的$为特殊字符而非普通字符串,此现象较为奇怪。

疑问

输出的命令与SSH终端中使用的命令看似一致,如何让C#实现与SSH终端相同的命令发送效果?


内容的提问来源于stack exchange,提问作者danieltakeshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 11:50:12