从输出中删除 chkconfig header

Remove chkconfig header from output

在我的 CentOS 机器上,我写了一个脚本来告诉我是否安装了服务。 这是脚本

count=$(chkconfig --list | grep -c "")
if [ $count = 0 ]; then
    echo "False"
else
    echo "True"
fi

问题是命令的输出总是包含 chkconfig 输出的起始行。例如这里是 script.sh network

的输出
[root@vm ~]# ./script.sh network

Note: This output shows SysV services only and does not include native
      systemd services. SysV configuration data might be overridden by native
      systemd configuration.

      If you want to list systemd services use 'systemctl list-unit-files'.
      To see services enabled on particular target use
      'systemctl list-dependencies [target]'.

True

似乎 count 变量正确地包含了 grep 出现的次数,但脚本将始终输出 chkconfig header 行,即使我只回显 "True" 或 "False"脚本。

为什么会这样?以及如何隐藏这些线条?

这是因为 chkconfig --list 最初 returns 从 header 到 stderr。只需使用 2>/dev/null:

使其静音
count=$(chkconfig --list 2>/dev/null | grep -c "")
#                        ^^^^^^^^^^^

另请注意,整个 if / else 块可以简化为:

chkconfig --list 2>/dev/null | grep -q "" && echo "True" || echo "False"

由于我们使用 grep-q 选项,它(来自 man grep如果找到任何匹配项,则立即以零状态退出.