Bash comparison between strings - equal but not equal for it

喜你入骨 提交于 2020-01-30 11:47:45

问题


I just wanted to do a really simple comparison between 2 strings in Bash :

stat=`curl -Is $url | head -n 1` 
echo $stat
if [ "$stat" = "HTTP/1.1 200 OK" ];then
    echo "$symbol is OK"
    echo $stat
    valide=$(( $valide + 1 ))
else
    echo "$symbol is 404"
    echo $stat
    err=$(( $err + 1 ))
fi

But even if "stat" is completely the same, the result stay that it does not equal :

HTTP/1.1 200 OK
AAA is 404
HTTP/1.1 200 OK

How can i modify my code ?

I had also a lot of errors with "/" ("unexpected operator", ...) in the string before arrive to this code sample, and i tried many different approaches like contains ("200") with the same result.

Thank you in advance !


回答1:


The curl output includes a CR at the end of the lines, you need to remove it.

stat=`curl -Is $url | head -n 1 | tr -d '\r'` 



回答2:


If you think there might be trailing characters (which you don't mind) then use [[ pattern matching instead:

# Try not to use `` anymore, backticks are hard to read
stat=$(curl -Is $url | head -n 1)  

# When debugging, use some sort of delimiter which shows leading or trailing whitespace     
echo "<$stat>"                          

# Variables inside [[ don't need to be quoted
# Adding a trailing * allows optional trailing characters
if [[ $stat == "HTTP/1.1 200 OK"* ]];then
    echo "$symbol is OK"
    echo $stat
    $(( valide++ ))          # You don't need the "$", just the variable name
else
    echo "$symbol is 404"
    echo $stat
    $(( err++ ))             # using a $ in (( )) can change the scan sequence
fi


来源:https://stackoverflow.com/questions/31635894/bash-comparison-between-strings-equal-but-not-equal-for-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!