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

为何sh/bash多行命令中无法添加注释?

Shell多行命令中注释失效的本质原因

我已查阅以下两篇Stack Overflow帖子:

  • 《How to put a line comment for a multi-line command》
  • 《Commenting in a Bash script inside a multiline command》

但它们并未从概念层面解释为何sh/bash多行命令中无法添加注释。

问题示例

#!/bin/bash

echo \
# comment
-n hello

在shellcheck检测时会得到如下警告:

-n hello
^-- SC2215 (warning): This flag is used as a command name. Bad line break or missing [ .. ]?

我的预期与困惑

我原本认为这可行的原因:

  • 我了解到注释会被程序忽略,因此不应产生影响

比如以下C语言程序可以正常运行:

#include <stdio.h>

int main() {

  printf("hello%d\n",
         // my comment
         3);
}

为何bash和sh中的情况与C语言存在本质差异?这种注释未被解释器完全忽略的现象是如何产生的?

我的猜想

  • shell在解析时仅忽略注释行,但在反斜杠后期望接续行,若此处是注释而非接续行就会出错,而非继续查看下一行非注释内容
  • C语言编译器在编译阶段就已移除注释,根本不会处理它们

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 14:57:10