问题
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