8

我发现在 bash 脚本中创建长管道非常强大,但我看到的主要缺点是似乎没有插入注释的方法。

例如,是否有一种向该脚本添加注释的好方法?

#find all my VNC sessions
ls -t $HOME/.vnc/*.pid                  \
    | xargs -n1                         \
    | sed 's|\.pid$||; s|^.*\.vnc/||g'  \
    | xargs -P50 --replace vncconfig -display {} -get desktop \
    | grep "($USER)"                    \
    | awk '{print $1}'                  \
    | xargs -n1 xdpyinfo -display       \
    | egrep "^name|dimensions|depths"
4

4 回答 4

24

让管道成为每行的最后一个字符并使用#代替\,如下所示:

ls -t $HOME/.vnc/*.pid | #comment here
   xargs -n1 | #another comment 
   ...
于 2011-02-24T05:42:14.243 回答
8

这也有效:

# comment here
ls -t $HOME/.vnc/*.pid |
 #comment here
 xargs -n1 |
 #another comment
 ...

基于https://stackoverflow.com/a/5100821/1019205。它归结为s/|//;s!\!|!

于 2017-02-14T00:24:19.290 回答
1

除非它们是非常长的管道,否则您不必内联评论,只需在顶部评论:

# Find all my VNC sessions.
#   xargs does something.
#   sed does something else
#   the second xargs destroys the universe.
#   :
#   and so on.

ls -t $HOME/.vnc/*.pid                  \
    | xargs -n1                         \
    | sed 's|\.pid$||; s|^.*\.vnc/||g'  \
    | xargs -P50 --replace /opt/tools/bin/restrict_resources -T1 \
            -- vncconfig -display {} -get desktop 2>/dev/null \
    | grep "($USER)"                    \
    | awk '{print $1}'                  \
    | xargs -n1 xdpyinfo -display       \
    | egrep "^name|dimensions|depths"

只要评论相对本地化,就可以了。所以我不会把它们放在文件的顶部(当然,除非你的管道是文件中的第一件事)或者在卫生纸上乱涂乱画,然后锁在你的办公桌上。

但是,当我查看一个块时,我做的第一件事就是查找该块之前的注释。即使在 C 代码中,我也不会对每一行进行注释,因为注释的目的主要是显示why和高级别的how.

于 2011-02-24T05:46:37.363 回答
0
#!/bin/bash

for pid in $HOME/.vnc/*.pid; do
    tmp=${pid##*/}
    disp=${tmp%.*}
    xdpyinfo -display "$disp" | # commment here
    egrep "^name|dimensions|depths"
done

如果它所做的只是附加'(用户)',我不明白需要vncconfig你随后删除它以调用xdpyinfo. 此外,所有这些管道都需要相当多的开销,如果您time的脚本与我的脚本相比,我认为您会发现性能相当,如果不是更快的话。

于 2011-02-24T18:00:08.940 回答