多行bash命令中的注释


32

这个单命令的BASH脚本文件很难理解,所以我想为每个动作写一个注释:

echo 'foo'     \
| sed 's/d/a/' \
| sed 's/e/b/' \
| sed 's/f/c/' \
> myfile

(sed只是一个例子,实际上是混用,trs和awk的组合)

我不想重复行,或者每个注释都离它适用的行很远。
但是同时BASH似乎不允许“在线”注释。

有解决这个问题的优雅方法吗?

Answers:


51

将管道放在行尾,并在其后加上注释:

$ echo 'foo' |
sed 's/f/a/' | # change first f to a
sed 's/o/b/' | # change first o to b
sed 's/o/c/'   # change second o to c
abc

这是有道理的,因为可能会出现一些问题
MrCholo

15

如果在注释管道多行命令时遇到此问题:

$ echo 'foo' |
sed -e 's/f/a/' `: # change first f to a` \
    -e 's/o/b/' `: # change first o to b` \
    -e 's/o/c/' `: # change second o to c`

除非您执行诸如自动评论之类的真正反常的事情,否则我看不出有什么理由比Mikel对于管道的回答更喜欢它,但是如果您确实想要:

$ echo 'foo' |
sed 's/f/a/' | `: # change first f to a` \
sed 's/o/b/' | `: # change first o to b` \
sed 's/o/c/'   `: # change second o to c`

要么:

$ echo 'foo' |
sed 's/f/a/' `: # change first f to a` |
sed 's/o/b/' `: # change first o to b` |
sed 's/o/c/' `: # change second o to c`

资料来源:http : //unix.derkeiler.com/Newsgroups/comp.unix.solaris/2005-07/0991.html


10

好吧,我更喜欢这样

echo 'foo' | {
  # change first f to a
  # you can add more lines of comment on the command options
  sed 's/f/a/'
} | {
  # change first o to b
  sed 's/o/b/'
} | {
  # change second o to c
  sed 's/o/c/' 
}
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.