在 bash 中比较字符串

在 bash 中比较字符串

我尝试编写以下脚本来比较两个 HTML 响应标头,但是else尽管通过打印存储在变量中的标头$a我得到了完全相同的值,但我还是遇到了条件。

#!/bin/bash
echo
echo "Connecting to www.cloudflare.com...";
curl -Is "https://www.cloudflare.com/" > file1.txt;
a=$(cat file1.txt | grep Server);
echo "$a";
echo
echo "Connecting directly to www.amazon.com...";
curl -Iks "https://www.amazon.com/" > file2.txt;
b=$(cat file2.txt | grep Server);
echo "$b";
echo

if [ "$a" == "Server: cloudflare-nginx" ]; then
    echo "This connection is going via CloudFlare"
else
    echo "This connection is NOT going via CloudFlare"
    echo "$a"
fi 

答案1

从命令返回的标题行在换行符之前curl有一个。^M您可以更改if以使用正则表达式:

if [[ "$a" =~ "Server: cloudflare-nginx" ]]; then
    echo "This connection is going via CloudFlare"
else
    echo "This connection is NOT going via CloudFlare"
    echo "$a"
fi

您还可以\r通过更改行来删除:

a=$(cat file1.txt | tr -d '\r' | grep '^Server:');

相关内容