多行 bash 命令中的注释

Nic*_*oul 41 bash comments sh pipe

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

echo 'foo'     \
| sed 's/d/a/' \
| sed 's/e/b/' \
| sed 's/f/c/' \
> myfile
Run Code Online (Sandbox Code Playgroud)

(sed 只是一个例子,实际上它是 grep、trs 和 awks 的混合体)

我讨厌不得不重复行,或者让每条评论远离它适用的行。
但同时 BASH 似乎不允许“内嵌”注释。

任何优雅的方法来解决这个问题?

Mik*_*kel 59

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

$ 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
Run Code Online (Sandbox Code Playgroud)


小智 19

如果您在评论管道多行命令时遇到此问题:

$ 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`
Run Code Online (Sandbox Code Playgroud)

除非你正在做一些像自动评论这样非常反常的事情,我看不出有什么理由比 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`
Run Code Online (Sandbox Code Playgroud)

或者:

$ 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`
Run Code Online (Sandbox Code Playgroud)

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


小智 15

嗯,我更喜欢这种方式,

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/' 
}
Run Code Online (Sandbox Code Playgroud)