Bash string (command output) equality test

前端 未结 2 1998
暖寄归人
暖寄归人 2020-12-17 21:19

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 b         


        
相关标签:
2条回答
  • 2020-12-17 21:50

    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.
    0 讨论(0)
  • 2020-12-17 21:57

    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
    
    0 讨论(0)
提交回复
热议问题