Remove chkconfig header from output

寵の児 提交于 2019-12-10 17:55:55

问题


On my CentOS machine I wrote a script which tells me whether a service is installed or not. Here is the script

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

The problem is that the output of the command always includes the starting lines of the chkconfig output. For example here is the output of 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

It seems that the count variable correctly contains the count of grep occurrences but the script will always output the chkconfig header lines, even though I echo only "True" or "False" in the script.

Why does this happen? And how to hide those lines?


回答1:


This is because chkconfig --list initially returns a header through stderr. Just silence it by using 2>/dev/null:

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

Note also that the whole if / else block can be reduced to a mere:

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

Since we use the -q option of grep which (from man grep) does exit immediately with zero status if any match is found.



来源:https://stackoverflow.com/questions/33694356/remove-chkconfig-header-from-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!