Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash string (command output) equality test

Tags:

bash

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?

like image 499
kliu Avatar asked Sep 16 '12 02:09

kliu


1 Answers

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
like image 106
glenn jackman Avatar answered Oct 23 '22 15:10

glenn jackman