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


当前回答

以下命令适用于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"

在上面的例子中。

其他回答

以下命令适用于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"

在上面的例子中。

在bash中:

#!/bin/bash
echo before comment
: <<'END'
bla bla
blurfl
END
echo after comment

END分隔符周围的“和”很重要,否则块内的内容(例如$(命令))将被解析并执行。

关于解释,请看这个和这个问题。

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

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

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

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

另一种模式是: 如果你的编辑器没有BLOCK评论选项,

打开编辑器的第二个实例(例如File=>New File…) 从您正在处理的上一个文件中,只选择要注释的部分 复制并粘贴到新的临时文件的窗口中… 打开编辑菜单,选择REPLACE,输入要替换的字符串'\n' 输入替换字符串:'\n#' 按下“替换全部”按钮

DONE

它适用于任何编辑器

你可以使用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(因为这是粘贴的快捷键)。