Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove chkconfig header from output

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?

like image 476
gvdm Avatar asked Apr 09 '26 20:04

gvdm


1 Answers

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.

like image 96
fedorqui 'SO stop harming' Avatar answered Apr 12 '26 08:04

fedorqui 'SO stop harming'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!