繁体   English   中英

如何在bash中使用双重grep比较(如果/否则)?

[英]How do I use a double grep comparison inside a bash if/else?

我如何在bash if / else中使用double 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

错误的原因是您无法使用[命令。 就像其他任何命令一样, [接受您无法通过不将其与参数分开而无法正确提供的参数。

[testPOSIX测试命令。 它可以对文件和字符串进行简单的测试。 在Bash中,建议您使用功能更强大的[[关键字。 [[可以进行模式匹配,使用起来更快捷,更安全(请参阅Bash FAQ 31进一步了解)。

但是,正如您在上面的解决方案中所看到的那样,您的情况不需要[[[ ,而只是一个if语句来询问grep退出状态 *。


退出状态 *:每个Unix进程都向其父级返回退出状态代码。 这是一个无符号的8位值,介于0到255之间(包括0和255)。 除非您专门使用值调用exit ,否则脚本将从上次执行的命令返回退出状态。 函数还使用return返回值。

尝试这个,

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 $HOSTNAME /etc/hosts]应该是if [ $(grep -q $HOSTNAME /etc/hosts) ] :在花括号和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"

当您确实要进行两个测试时,请考虑2个独立的if语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM