是否有一种简单的方法来注释掉shell脚本中的代码块?


当前回答

在vscode中ctrl+K+C (ctrl+K+U取消注释)。

其他回答

sunny256给出的已接受的答案中的here-doc技巧的一个变体是使用Perl关键字进行注释。如果您的注释实际上是某种文档,那么您可以开始在注释块中使用Perl语法,这允许您将其打印出来,将其转换为手册页,等等。

就shell而言,你只需要将'END'替换为'=cut'。

echo "before comment"
: <<'=cut'
=pod

=head1 NAME
   podtest.sh - Example shell script with embedded POD documentation

etc.

=cut
echo "after comment"

(参见“在shell脚本中嵌入文档”)

你可以使用:

if [ 1 -eq 0 ]; then
  echo "The code that you want commented out goes here."
  echo "This echo statement will not be called."
fi

可以将注释代码放在函数中。这样做的一个好处是,您可以通过在定义之后调用函数来“取消注释”。

除非您打算通过调用函数来“取消注释”,否则函数内的文本不必在语法上正确。

ignored() {
  echo this is  comment
  echo another line of comment
}

许多GUI编辑器允许您选择一个文本块,然后按“{”自动在所选代码块周围加上花括号。

以下命令适用于sh、bash、ksh和zsh。

注释的代码块可以放在BEGINCOMMENT和ENDCOMMENT中:

[ -z $BASH ] || shopt -s expand_aliases
alias BEGINCOMMENT="if [ ]; then"
alias ENDCOMMENT="fi"

BEGINCOMMENT
  echo "This line appears in a commented block"
  echo "And this one too!"
ENDCOMMENT

echo "This is outside the commented block"

执行上述代码将导致:

This is outside the commented block

例如,为了取消注释所注释的代码块

alias BEGINCOMMENT="if : ; then"

而不是

alias BEGINCOMMENT="if [ ]; then"

在上面的例子中。

你可以使用Vi/Vim的可视块模式,它是为这样的东西设计的:

Ctrl-V  
Highlight first element in rows you want commented  
Shift-i  
#  
esc  

不加评论的是:

Ctrl-V  
Highlight #'s  
d  
l  

这是vi做这类事情的交互式方式,而不是计算或读取行号。

最后,在Gvim中使用ctrl-q进入Visual Block模式,而不是ctrl-v(因为这是粘贴的快捷键)。