如何在Shell脚本中注释多行命令?


19

调用长而繁琐的命令时,将它们写在shell脚本中是一个好习惯。有没有简单的方法可以在此类脚本中注释行?我尝试了以下方法,但均无济于事。

# the \ is also commented out, resulting in "command" and "--good-switch".
command \
  #--bad-switch \
  --good-switch \

# seems to send an extra argument to the command
command \
  \ #--bad-switch \
  --good-switch
shell 

1
第二个引起空格作为参数发送(\ 转义下一个字符,该字符“隐藏”换行符,但使空格有意义)。
geekosaur 2011年

Answers:


14

这可能是一个选择:将命令和args存储在数组中,然后在执行后执行

# build the command
cmd=( ls
        -F
      # -a   # comment out this option temporarily
        -l
    )
# $cmd is now an array with 3 elements

# execute it
"${cmd[@]}"

bash仅是……
Socob

3

我总是在命令后移动注释的内容。

command \
  --good-switch
# --bad-switch          with explanation here, if needed

0

问题在于,在分析行之前就删除了斜杠,因此第一个命令就象您编写的一样被分析command #--bad-switch --good-switch。如果您有很长的命令序列,则可以例如在其上方或下方编写逐行注释块,依次解释每个注释块,也可以将参数存储在变量中(尽管这通常会引起引用的麻烦)特殊的角色)。


1
事实并非如此。--good-switch被解释为命令。


0

注释会制动连接的线链,因此最简单的解决方案是将注释的线移动到列表的末尾。

command \
  --good-switch \
  # --bad-switch \

如果您不想更改顺序,则可以使用:命令(冒号实用程序,不执行任何操作)使连接的线路保持完整:

command \
  `: --bad-switch `\
  --good-switch \

我对此进行了测试:

function command { 
  echo "num args:" $#;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.