我有一个简单的脚本来检查网页是否包含指定的字符串.看起来像:
#!/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
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我希望得到"OK",但得到了"错误".
它出什么问题了?
如果我使用if [$ res =="0"],它可以工作.如果我只使用res ="0"而不是res = curl...
,它也可以获得所需的结果.
为什么会有这些差异?
gle*_*man 19
你可以看到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
Run Code Online (Sandbox Code Playgroud)
甚至没有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
Run Code Online (Sandbox Code Playgroud)