除了
#
之外,任何人都可以建议如何注释 shell 脚本中的特定行吗?
假设我想评论五行。除了在每一行添加
#
之外,还有其他方法来注释这五行吗?
您可以使用条件注释脚本的部分。
例如以下脚本:
DEBUG=false
if ${DEBUG}; then
echo 1
echo 2
echo 3
echo 4
echo 5
fi
echo 6
echo 7
会输出:
6
7
为了取消注释代码部分,您只需注释变量即可:
#DEBUG=false
(这样做会打印数字 1 到 7。)
是的(尽管这是一个令人讨厌的黑客)。您可以使用 heredoc 因此:
#!/bin/sh
# do valuable stuff here
touch /tmp/a
# now comment out all the stuff below up to the EOF
echo <<EOF
...
...
...
EOF
这是在做什么? A
heredoc
将终止符(在本例中为 EOF)之前的所有输入输入到指定命令中。这样你就可以将你想要注释掉的代码括起来
echo <<EOF
...
EOF
它将获取两个 EOF 之间包含的所有代码并将它们提供给
echo
(echo
不会从 stdin 读取,因此所有代码都会被丢弃)。
请注意,通过上述内容,您可以在
heredoc
中放入任何内容。它不必是有效的 shell 代码(即它不必正确解析)。
这非常令人讨厌,我仅将其作为兴趣点提供。你不能做 C 的同等工作
/* ... */
对于单行注释,在行首添加 #
对于多行注释,请从要开始的位置添加 '(单引号),并在要结束注释行的位置添加 '(再次单引号)。
您必须依赖“#”,但为了使 vi 中的任务更容易,您可以执行以下操作(先按 escape):
:10,20 s/^/#
10 和 20 是要注释掉的行的起始行号和结束行号
完成后撤消:
:10,20 s/^#//
单行评论:
以“#”开头
例如:
# This whole line is a comment and will not be executed
多行评论:
以“<
例如:
<<commentName
Now this whole section is a comment,
until you specify the comment name again
to end the comment section.
commentName
另存为
shellcommenttest.sh
,使用 chmod +x shellcommenttest.sh
使其可执行,然后使用 ./shellcommenttest.sh
运行
echo Comment demo, there should be no output after this line.
# option 1, also works in zsh cli
false && my comment
# option 2
if [[ ! 0 ]]; then
my comment
can be multiline
fi
# Pretty but don't work in Zsh CLI
# option 3
# my comment
# option 4, heredoc
<<EOF
my comment
can be multiline
EOF