13

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?

0

2 Answers 2

24

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, it's good solution. But, as my question, I just want know why [[ $res == "0" ]] isn't work in this case, so that I can avoid making the same mistakes in the future
what do you see with od -c <<< "$res"? Are there extra whitespace characters?
Yes, you are right, there are whitespaces in wc output. Thanks.
1

I found the answer in glenn jackman's help.

I get the following points in this question:

  • wc -l 's output contains whitespaces.
  • Debugging with echo "$var" instead of echo $var
  • [[ preserves the literal value of all characters within the var.
  • [ expands var to their values before perform, it's because [ is actually the test cmd, so it follows Shell Expansions rules.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.