如何在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
但收到错误消息:*too many arguments*
怎么了?
这是您应该执行的:
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(包括0到255)。您的脚本返回上一个命令的退出状态执行,除非您特别使用值调用exit
。函数还使用return
返回值。
您的语法失败:if [grep -q $HOSTNAME /etc/hosts]
应该是if [ $(grep -q $HOSTNAME /etc/hosts) ]
:在brachets和grep之间加空格作为子命令
这仍然不起作用,因为if
期望的是要测试的东西,而不是测试的结果。我通常使用if [ $(grep -c string file) -gt 0 ]
,但您也可以使用if [ -n "$(grep string file)" ]
。
我想你希望主机和ip在同一条线上。在这种情况下使用:
if [ -n "$(grep -E "${IP}.*${HOSTNAME}" /etc/hosts)" ]; then
echo "Found"
fi
# or (using the grep -q)
grep -Eq "${IP}.*${HOSTNAME}" /etc/hosts
if [ $? -eq 0 ]; then
# or (shorter, harder to read for colleages, using the grep -q)
grep -Eq "${IP}.*${HOSTNAME}" /etc/hosts)" && echo "Found"
当你真的想要两个测试时,考虑两个独立的if语句。
试试这个,
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