如何在 bash if/else 中使用双重 grep 比较?
我想跑:
if [grep -q $HOSTNAME /etc/hosts] && [grep -q $IP /etc/hosts]
then
echo $HOSTNAME and $IP is found into /etc/hosts, test passed OK.
else
# code if not found
echo The Hostname $HOSTNAME'/'IP $IP is not found in /etc/hosts, please append it manually.
exit 1;
fi
但收到错误消息:*太多参数*
怎么了?
最佳答案
这是你应该执行的:
if grep -q "foo" /etc/hosts && grep -q "bar" /etc/hosts; then
# Both foo and bar exist within /etc/hosts.
else
# Either foo or bar or both, doesn't exist in /etc/hosts.
fi
你的错误原因是你没有使用[
命令。
就像任何其他命令一样,[
接受您未能正确提供的参数,因为您没有将它与其参数分开。
[
或 test
是 POSIX 测试命令。它可以对文件和字符串进行简单的测试。在 Bash 中,我建议您使用更强大的 [[
关键字。 [[
可以进行模式匹配,使用起来更快更安全(进一步阅读Bash FAQ 31)。
不过,正如您在我上面的解决方案中看到的那样,您的情况不需要 [
或 [[
,而只是一个 if
语句请求 grep
的退出状态*。
退出状态*:每个 Unix 进程都会向其父进程返回一个退出状态代码。这是一个无符号的 8 位值,一个从 0 到 255 的数字。您的脚本返回最后一个命令的退出状态
执行,除非您特别调用 exit
并指定一个值。函数也返回值,使用 return
。
关于linux - 如何在 bash if/else 中使用双重 grep 比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36531452/