linux - 如何在 bash if/else 中使用双重 grep 比较?

标签 linux bash shell

如何在 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

你的错误原因是你没有使用[命令。 就像任何其他命令一样,[ 接受您未能正确提供的参数,因为您没有将它与其参数分开。

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

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


退出状态*:每个 Unix 进程都会向其父进程返回一个退出状态代码。这是一个无符号的 8 位值,一个从 0 到 255 的数字。您的脚本返回最后一个命令的退出状态 执行,除非您特别调用 exit 并指定一个值。函数也返回值,使用 return

关于linux - 如何在 bash if/else 中使用双重 grep 比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36531452/

相关文章:

regex - 在带sed的括号前放置逗号

linux - Bash命令打开最大的文件

linux - 将 shell 脚本的输出重定向到文本文件

powershell - 如何在Powershell中检查多个变量的条件

linux - 如何检查文件夹中的所有文件是否具有相同格式

linux - 更改 git 在 linux 上的安装位置

linux - shell 脚本中未捕获输出

linux - Docker 容器立即退出

bash - 如何在 Perl 脚本中重新加载 Bash 环境变量?

linux - 查找与某个 'count of commits' 匹配的所有 git 提交