“服务”带来意想不到的结果grep`

“服务”带来意想不到的结果grep`
$ sudo service --status-all | fgrep -e 'bluetooth'
 [ ? ]  alsa-utils
 [ ? ]  binfmt-support
 [ + ]  bluetooth
 [ ? ]  cpufrequtils
 [ ? ]  cryptdisks
 [ ? ]  cryptdisks-early
 [ ? ]  hdparm
 [ ? ]  hwclock.sh
 [ ? ]  kmod
 [ ? ]  loadcpufreq
 [ ? ]  networking
 [ ? ]  plymouth
 [ ? ]  plymouth-log
 [ ? ]  pppd-dns
 [ ? ]  udev-finish
 [ ? ]  virtualbox-guest-x11
$ sudo service bluetooth stop
[ ok ] Stopping bluetooth: /usr/sbin/bluetoothd.
$ sudo service --status-all | fgrep -e 'bluetooth'
 [ ? ]  alsa-utils
 [ ? ]  binfmt-support
 [ - ]  bluetooth
 [ ? ]  cpufrequtils
 [ ? ]  cryptdisks
 [ ? ]  cryptdisks-early
 [ ? ]  hdparm
 [ ? ]  hwclock.sh
 [ ? ]  kmod
 [ ? ]  loadcpufreq
 [ ? ]  networking
 [ ? ]  plymouth
 [ ? ]  plymouth-log
 [ ? ]  pppd-dns
 [ ? ]  udev-finish
 [ ? ]  virtualbox-guest-x11

service | grep为什么只有 1 行(每个输出集中)与模式匹配,而我得到的输出行却不止 1 行grep?这些行的开头有什么(不好的)魔力吗[?]?或者,我错过了什么?

FWIW,我正在跑步

$ date
Tue Nov 28 20:51:46 MST 2017
$ uname -rsv
Linux 3.16.0-4-amd64 #1 SMP Debian 3.16.43-2+deb8u5 (2017-09-19)
$ lsb_release -ds
LMDE 2 Betsy
$ cat /etc/debian_version
8.9
$ gcc --version | head -n 1
gcc (Debian 4.9.2-10) 4.9.2

答案1

在我看来@Sundeep 是正确的。

如果您查看脚本是否service存在导致此行为的重定向

if ! is_ignored_file "${SERVICE}" \
    && [ -x "${SERVICEDIR}/${SERVICE}" ]; then
    out=$(env -i LANG="$LANG" LANGUAGE="$LANGUAGE" LC_CTYPE="$LC_CTYPE" LC_NUMERIC="$LC_NUMERIC" LC_TIME="$LC_TIME" LC_COLLATE="$LC_COLLATE" LC_MONETARY="$LC_MONETARY" LC_MESSAGES="$LC_MESSAGES" LC_PAPER="$LC_PAPER" LC_NAME="$LC_NAME" LC_ADDRESS="$LC_ADDRESS" LC_TELEPHONE="$LC_TELEPHONE" LC_MEASUREMENT="$LC_MEASUREMENT" LC_IDENTIFICATION="$LC_IDENTIFICATION" LC_ALL="$LC_ALL" PATH="$PATH" TERM="$TERM" "$SERVICEDIR/$SERVICE" status 2>&1)
    retval=$?
    if echo "$out" | egrep -iq "usage:"; then
        #printf " %s %-60s %s\n" "[?]" "$SERVICE:" "unknown" 1>&2
        echo " [ ? ]  $SERVICE" 1>&2          #<-------------------HERE
        continue
    else
    if [ "$retval" = "0" -a -n "$out" ]; then
        #printf " %s %-60s %s\n" "[+]" "$SERVICE:" "running"
        echo " [ + ]  $SERVICE"
        continue
    else
        #printf " %s %-60s %s\n" "[-]" "$SERVICE:" "NOT running"
        echo " [ - ]  $SERVICE"
        continue
    fi
fi

重定向是针对错误情况的(服务不支持调用status),因此虽然可见输出是[ ? ]“juju”,但实际上是绕过 grep 的重定向。

在命令行上测试这个......

~$ echo "banana" | grep bluetooth       #nothing echoed
~$ echo "banana" 1>&2 | grep bluetooth  #bingo, get a banana
banana

相关内容