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

/* comment1
   comment2 
   comment3
*/`

我怎么能那样做呢?


当前回答

下面是我如何在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

其他回答

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

下面是我如何在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

直白地说 注释掉 一段代码 我做

: | | { 块 的代码 }

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

暂时阻塞脚本的一部分:

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

使用:'打开'和'关闭。

例如:

: '
This is a
very neat comment
in bash
'