如果命令输出包含某个字符串,我如何测试(在一行中) ?

在一行 bash 中,当 /usr/local/bin/monit --version的输出不完全包含 5.5时,如何返回0的退出状态,当它包含 5.5时,如何返回1的退出状态?

107225 次浏览
! /usr/local/bin/monit --version | grep -q 5.5

(grep returns an exit-status of 0 if it finds a match, and 1 otherwise. The -q option, "quiet", tells it not to print any match it finds; in other words, it tells grep that the only thing you want is its return-value. The ! at the beginning inverts the exit-status of the whole pipeline.)

Edited to add: Alternatively, if you want to do this in "pure Bash" (rather than calling grep), you can write:

[[ $(/usr/local/bin/monit --version) != *5.5* ]]

([[...]] is explained in §3.2.4.2 "Conditional Constructs" of the Bash Reference Manual. *5.5* is just like in fileglobs: zero or more characters, plus 5.5, plus zero or more characters.)

[ $(/usr/local/bin/monit --version) == "5.5" ]

eg-1: check for success

[ $(/usr/local/bin/monit --version) == "5.5" ] && echo "OK"

eg-2: check for failure

    [ $(/usr/local/bin/monit --version) == "5.5" ] || echo "NOT OK"

or, to just check if the output contains 5.5:

[[ $(/usr/local/bin/monit --version) =~ "5.5" ]] || echo "NOT OK"

Test the return value of grep:

sudo service xyz status | grep 'not' &> /dev/null
if [ $? == 0 ]; then
echo "whateveryouwant"
fi

I would recommend cron, it works fine with SALT stack