Answers:
测试grep的返回值:
./somecommand | grep 'string' &> /dev/null
if [ $? == 0 ]; then
echo "matched"
fi
习惯上是这样的:
if ./somecommand | grep -q 'string'; then
echo "matched"
fi
并且:
./somecommand | grep -q 'string' && echo 'matched'
=要是一个比较运算符,而不是==; 参见pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html
grep 'string' &>/dev/null它不仅不兼容POSIX,而且执行速度也较慢(如果string出现在较长的输出流中较早)grep -q string。[这里有一个警告,如果您要确保somecommand即使在发出之后仍然保持运行string,在这种情况下,使用grep -q-通过关闭其stdin并在string看到第一个实例后退出-会适得其反]。(Re:“非POSIX兼容”,&>是扩展-参见pubs.opengroup.org/onlinepubs/009695399/utilities/…描述了POSIX要求的重定向支持)。
测试$?是一种反模式
if ./somecommand | grep -q 'string'; then
echo "matched"
fi
grep -Fxq F表示固定(未解释),x表示整行
$?是反模式?
$?目的set -e或ERR陷阱的考虑,测试并未将前面的命令设置为“已检查” ,因此,在您希望程序稍后仅返回故意错误的路径的情况下,您的程序可以退出。另一个$?是不稳定的全球状态,很容易被偶然抛弃其价值。例如,如果您添加一行类似的日志echo "Exit status is $?",中的新值$?将成为的退出状态echo。
另一种选择是在命令输出上检查正则表达式匹配。
例如:
[[ "$(./somecommand)" =~ "sub string" ]] && echo "Output includes 'sub string'"
干净的if / else条件shell脚本:
if ./somecommand | grep -q 'some_string'; then
echo "exists"
else
echo "doesn't exist"
fi