我最近开始研究shell脚本,我希望能够在shell脚本中注释出一组行。我的意思是,就像在C/Java的情况下:
/* comment1
comment2
comment3
*/`
我怎么能那样做呢?
我最近开始研究shell脚本,我希望能够在shell脚本中注释出一组行。我的意思是,就像在C/Java的情况下:
/* comment1
comment2
comment3
*/`
我怎么能那样做呢?
当前回答
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
其他回答
使用:'打开'和'关闭。
例如:
: '
This is a
very neat comment
in bash
'
简单的解决方案,不太聪明:
暂时阻塞脚本的一部分:
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
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
我尝试了选择的答案,但发现当我运行一个shell脚本时,整个事情都打印到屏幕上(类似于jupyter笔记本如何打印出“xx”引号中的所有内容),并在结束时出现错误消息。它什么都没做,但是很吓人。后来我在编辑的时候意识到单引号可以跨越多行。所以. .让我们把这个块赋值给一个变量。
x='
echo "these lines will all become comments."
echo "just make sure you don_t use single-quotes!"
ls -l
date
'