I have a simple script to check whether webpage contains a specified string. It looks like:
#!/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
As you can see, I am looking to get "OK", but got a "Wrong".
What's wrong with it?
If I use if [ $res == "0" ], it works. If I just use res="0" instead of res=curl...
, it also can obtain the desired results.
Why are there these differences?
You could see what res
contains: echo "Wrong: res=>$res<"
If you want to see if some text contains some other text, you don't have to look at the length of grep output: you should look at grep's return code:
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
Or even without 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With