在Bash中创建多行评论的方法?

时间:2017-04-01 14:33:09

标签: shell comments multiline

我最近开始研究shell脚本,我希望能够在shell脚本中注释掉一组行。我的意思是在C / Java的情况下:

/* comment1
   comment2 
   comment3
*/`

我怎么能这样做?

10 个答案:

答案 0 :(得分:251)

使用: '打开,'关闭。

例如:

: '
This is a
very neat comment
in bash
'

答案 1 :(得分:92)

bash中的多行评论

: <<'END_COMMENT'
This is a heredoc (<<) redirected to a NOP command (:).
The single quotes around END_COMMENT are important,
because it disables variable resolving and command resolving
within these lines.  Without the single-quotes around END_COMMENT,
the following two $() `` commands would get executed:
$(gibberish command)
`rm -fr mydir`
comment1
comment2 
comment3
END_COMMENT

答案 2 :(得分:19)

Bash不提供内置功能,但有使用现有bash语法的黑客攻击。最简单的是使用HEREDOC,但要明确你正在做什么,并在任何地方使用相同的HEREDOC标记:

<< --MULTILINE-COMMENT--
line 1
line 2

line 3
line 4
--MULTILINE-COMMENT--

有些帖子提到必须引用HEREDOC标记以避免一些shell解析副作用。如果您在评论中使用反引号,我只发现这是必要的。即使评论中提到set -o verbose$variables,也无需引用标记。 YMMV。

如果你使用另一个答案中提到的: '方法,那么通过元评论记录它是什么,在任何地方使用相同的元评论,并记住将'内任何出现的: 'Multiline comment: line 1 line 2 we''re going to try this eventually line 3 ' 加倍注释(语法着色编辑器会使其显而易见):

{{1}}

两者都是黑客,所以他们将来可以打破脚本。

肯定还有其他技术,但似乎并不是传统的技术。这样做的方式。

答案 3 :(得分:14)

在阅读完其他答案后,我想到了以下内容,恕我直言,这很明显是一则评论。特别适用于脚本内使用信息:

<< ////

Usage:
This script launches a spaceship to the moon. It's doing so by 
leveraging the power of the Fifth Element, AKA Leeloo.
Will only work if you're Bruce Willis or a relative of Milla Jovovich.

////

作为程序员,斜线序列立即在我的大脑中记录为注释(即使斜线通常用于行注释)。

当然,"////"只是一个字符串。前缀和后缀中的斜杠数必须相等。

答案 4 :(得分:3)

您对此有何看法?

tqdm

答案 5 :(得分:1)

这是我在bash中进行多行注释的方法。

这种机制有两个优点,我很欣赏。一种是注释可以嵌套。另一个是可以通过简单注释掉启动行来启用块。

#!/bin/bash
# : <<'####.block.A'
echo "foo {" 1>&2
fn data1
echo "foo }" 1>&2
: <<'####.block.B'
fn data2 || exit
exit 1
####.block.B
echo "can't happen" 1>&2
####.block.A

在上面的示例中,“ B”块被注释掉,但是“ A”块中不是“ B”块的部分未被注释掉。

运行该示例将产生以下输出:

foo {
./example: line 5: fn: command not found
foo }
can't happen

答案 6 :(得分:1)

简单的解决方案,不够聪明:

暂时阻止脚本的一部分:

if false; then
    while you respect syntax a bit, please
    do write here (almost) whatever you want.
    but when you are
    done # write
fi

有点复杂的版本:

time_of_debug=false # Let's set this variable at the beginning of a script

if $time_of_debug; then # in a middle of the script  
    echo I keep this code aside until there is the time of debug!
fi

答案 7 :(得分:1)

我尝试了选择的答案,但是发现当我运行包含它的shell脚本时,整个东西都被打印到了屏幕上(类似于jupyter笔记本如何打印'''xx'''引号中的所有内容),并且出现了错误消息末尾。它什么也没做,但是:吓人。然后我意识到在编辑它时,单引号可以跨越多行。因此,让我们只将块分配给变量即可。

x='
echo "these lines will all become comments."
echo "just make sure you don_t use single-quotes!"

ls -l
date

'

答案 8 :(得分:0)

#我喜欢懒惰和简单。我将#与有趣的解决方法结合使用:

1 PRESS:]查找ctrl + F或cmd + F或其他内容[以触发查找功能

2在查找字段中使用正则表达式,例如:(^.+)

3替换为:# $1,或者如果您更喜欢#$1


#注意:您的编辑器中可能没有这三个步骤。在这种情况下,请使用在线正则表达式工具(出于政策原因不能在此建议):

  1. 选择并复制文本,然后将其粘贴到在线正则表达式工具中
  2. 使用(^.+)作为正则表达式,使用#$1#\1作为替换模式
  3. 选择,复制文本并将其粘贴回开始的地方

#享受您的哈希!

答案 9 :(得分:0)

在普通的bash中 注释掉 代码块 我愿意

:||{ 堵塞 代码 }