从输出中删除chkconfig标头

gvd*_*vdm 3 linux bash centos7

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

count=$(chkconfig --list | grep -c "$1")
if [ $count = 0 ]; then
    echo "False"
else
    echo "True"
fi
Run Code Online (Sandbox Code Playgroud)

问题是命令的输出总是包括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
Run Code Online (Sandbox Code Playgroud)

似乎count变量正确包含grep出现次数,但脚本将始终输出chkconfig标题行,即使我在脚本中仅回显"True"或"False".

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

fed*_*qui 5

这是因为chkconfig --list最初返回一个标题stderr.只需使用2>/dev/null以下方法使其静音

count=$(chkconfig --list 2>/dev/null | grep -c "$1")
#                        ^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

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

chkconfig --list 2>/dev/null | grep -q "$1" && echo "True" || echo "False"
Run Code Online (Sandbox Code Playgroud)

因为如果找到任何匹配,我们使用其中(from )的-q选项立即退出并且状态为零.grepman grep