【问题标题】:BASH comments: Difference between # (hash) -vs- : (colon) commentingBASH 评论:#(散列)-vs- 之间的区别:(冒号)评论
【发布时间】:2021-08-03 01:27:40
【问题描述】:

在 bash GNU bash,版本 4.2.46(2)-release (x86_64-redhat-linux-gnu) 或任何稳定版本中, 您可以使用#: 发表评论

这2个和用处有什么区别?

我注意到# 注释使整行成为注释,而: 范围/效果仅在到达第一个\n; 字符(在给定行中)之前。

[gigauser@someserver ~]$ # this is a # comment; echo this will not print
[gigauser@someserver ~]$ : this is a : comment; echo this will print
this will print

在以下代码中,为什么最后 2 个 cmets 没有按预期工作以将它们视为注释(尽管 ::: 之后有效?

[gigauser@someserver ~]$ #
[gigauser@someserver ~]$ ##
[gigauser@someserver ~]$ ####
[gigauser@someserver ~]$ ####
[gigauser@someserver ~]$ : : : : : : : : : :
[gigauser@someserver ~]$ #
[gigauser@someserver ~]$ # # #
[gigauser@someserver ~]$ ####
[gigauser@someserver ~]$
[gigauser@someserver ~]$ :
[gigauser@someserver ~]$ : :
[gigauser@someserver ~]$ : : : : : : : : : : : : ::::::::
[gigauser@someserver ~]$ : : :::::
[gigauser@someserver ~]$
[gigauser@someserver ~]$
[gigauser@someserver ~]$ ::
-bash: ::: command not found
[gigauser@someserver ~]$ :::::
-bash: :::::: command not found
[gigauser@someserver ~]$

【问题讨论】:

标签: linux bash unix command comments


【解决方案1】:

: 根本不是评论,它是一个不做任何事情的命令。最重要的区别在于,由于它是一个命令,因此它之后的任何 shell 语法都将被解释和执行。例如:

: Check whether x > 1

这里> 1 部分将被解释为输出重定向,因此它将创建一个名为“1”的文件并将(空)输出重定向到它。如果是x < 1,它会尝试打开“1”进行输入并且(可能)失败。

: Check permissions on the user's home directory

这里' 将被解释为开始一个单引号字符串(这将是: 的一个参数),并且可能会对脚本其余部分的解析方式造成严重破坏。

: Test for completion (again)

产生-bash: syntax error near unexpected token `('

: 命令有时很有用,如果您希望执行参数扩展(因为它们的副作用),但又不想对结果做任何事情。

: ${VAR:=defaultvalue}

这里,如果$VAR 尚未设置为非空白值,:= 修饰符会将其设置为“默认值”。这基本上是

if [ -z "$VAR" ]; then
    VAR=defaultvalue
fi

编辑:

正如 AKS 在 a link in the comments 中指出的那样,: 的一个效果是您可以使用它和带有引号分隔符的 here-document 制作块 cmets。这与# 在功能上有所不同。

: <<'COMMENT'
This block doesn't do anything, effectively a multi line comment block.
It'll also not get identified by linters and syntax highlighters as a comment.
COMMENT

常规 cmets 必须以 # 开头。

(注意:与链接所说的相反,您可以在 here-doc 分隔符上使用单引号或双引号,即 &lt;'COMMENT'&lt;"COMMENT"。如果分隔符上没有某种引号,则shell 将尝试解析和扩展它在文档中找到的任何$ 或反引号表达式,这会再次造成麻烦。)

【讨论】:

  • 感谢您的解释。
猜你喜欢
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
  • 2011-02-01
  • 2011-04-15
  • 2014-08-27
  • 2014-08-12
相关资源
最近更新 更多