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:
Or even without grep:
I found the answer in glenn jackman's help.
I get the following points in this question:
wc -l
's output contains whitespaces.echo "$var"
instead ofecho $var
[[
preserves the literal value of all characters within the var.[
expands var to their values before perform, it's because [ is actually thetest
cmd, so it follows Shell Expansions rules.