Bash string (command output) equality test

2020-02-11 02:45发布

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?

标签: bash
2条回答
家丑人穷心不美
2楼-- · 2020-02-11 03:01

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
查看更多
地球回转人心会变
3楼-- · 2020-02-11 03:18

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.
查看更多
登录 后发表回答