微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Bash字符串(命令输出)相等测试

我有一个简单的脚本来检查网页是否包含指定的字符串.看起来像:
#!/bin/bash
res=`curl -s "http://www.google.com" | grep "foo bar foo bar" | wc -l`
if [[ $res == "0" ]]; then
    echo "OK"
else
    echo "Wrong"
fi

正如你所看到的,我希望得到“OK”,但得到了“错误”.

它出什么问题了?

如果我使用if [$res ==“0”],它可以工作.如果我只使用res =“0”而不是res = curl …,它也可以获得所需的结果.

为什么会有这些差异?

您可以看到res包含的内容:echo“Wrong:res => $res<” 如果你想看看某些文本是否包含其他文本,你不必查看grep输出的长度:你应该看一下grep的返回码:
string="foo bar foo bar"
if curl -s "http://www.google.com" | grep -q "$string"; then
    echo "'$string' found"
else
    echo "'$string' not found"
fi

甚至没有grep:

text=$(curl -s "$url")
string="foo bar foo bar"
if [[ $text == *"$string"* ]]; then
    echo "'$string' found"
else
    echo "'$string' not found in text:"
    echo "$text"
fi

原文地址:https://www.jb51.cc/bash/384201.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐