你不能在sh中的多行命令中添加注释。

huangapple go评论66阅读模式
英文:

Why can you not have comments in multi-line commands in sh?

问题

I've looked at these posts:

但它在概念上没有解释为什么不行。

例如:

#!/bin/bash

echo \
# 注释
-n hello

shellcheck.net 上显示:

> -n hello
^-- SC2215 (warning): 此标志用作命令名。换行错误或缺少 [ .. ]?

我认为它应该没问题的原因是:

  • 我学过程序会忽略注释(因此不应有任何影响)

例如,一个 C 程序:

#include <stdio.h>

int main() {

  printf("hello%d\n",
		 // 我的注释
		 3);
}

为什么在 bashsh 中基本不同?

是如何解释这个问题的(为什么解释器没有完全忽略注释)?

我的想法是:

  • Shell 在解析时简单地忽略带有注释的行,但期望在反斜杠之后有一个继续行,由于某种原因(为什么?)如果有注释(本应被忽略)而不是查看下一行(未注释)而是中断
  • C 编译器甚至从未看到注释,因为它们在编译阶段消失
英文:

I've looked at these posts:

but it doesn't answer conceptually why not.

For example:

#!/bin/bash

echo \
# comment
-n hello

on shellcheck.net yields:

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

Reason I thought it would be okay:

  • I had learned comments are ignored by programs (and so it should make no difference)

For example, a C program:

#include <stdio.h>

int main() {

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

Why is this fundamentally different in bash and sh?

How is it being interpreted that causes this (with comments not being completely ignored by the interpreter)?

My idea:

  • the shell simply ignores lines with comments while parsing, but expects a continuation line after the backslash and for some reason (why?) breaks if a comment (which should be ignored) is there instead of looking at the next (uncommented) line
  • C compiler never even sees comments because they are gone by compilation stage

答案1

得分: 1

对于 POSIX shell,这个行为在第 2.3 节的“标记识别”1中有定义:

> 如果当前字符是一个 ''#'',则它和之后的所有字符,直到但不包括下一个“换行符”,都将被丢弃作为注释。结束行的“换行符”不被视为注释的一部分。

bash 简单地采用了这个约定,以便更容易将脚本从 sh 移植到 bash。从我看到的情况来看,zsh 也在做同样的事情,很可能 ksh 也是如此。

英文:

For POSIX shell, this behaviour is defined here in chapter 2.3 Token Recognition:

> If the current character is a '#', it and all subsequent characters up to, but excluding, the next newline shall be discarded as a comment. The newline that ends the line is not considered part of the comment.

bash simply took over this convention to make it easier to port scripts from sh to bash. From what I see, zsh is doing the same, and most likely ksh too.

huangapple
  • 本文由 发表于 2023年5月17日 10:30:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76268204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定