问题
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