将变量与 Bash 中的字符串进行比较

Comparing variable to string in Bash

我已经尝试了 How do I compare two string variables in an 'if' statement in Bash?

的建议

但这对我不起作用。

我有

if [ "$line" == "HTTP/1.1 405 Method Not Allowed" ]
then
    <do whatever I need here>
else
    <do something else>
fi

无论如何,它总是去else语句。我什至在这之前回显了 $line,然后复制并粘贴了结果,只是为了确保字符串是正确的。

如能提供任何帮助说明为什么会发生这种情况,我们将不胜感激。

如果您从兼容的 HTTP 网络连接中读取该行,它几乎可以肯定在末尾有一个回车 return 字符(\x0D,通常表示为 \r),因为HTTP 协议使用 CR-LF 终止行。

因此您需要删除或忽略 CR。

这里有几个选项,如果您使用 bash:

  1. 使用 bash 查找和替换语法从行中删除 CR(如果存在):

    if [ "${line//$'\r'/}" = "HTTP/1.1 405 Method Not Allowed" ]; then
    
  2. 使用全局比较进行前缀匹配(需要 [[ 而不是 [,但无论如何更好):

    if [[ "$line" = "HTTP/1.1 405 Method Not Allowed"* ]]; then
    
  3. 您可以在 [[ 中使用正则表达式比较来进行子字符串匹配,可能使用正则表达式:

    if [[ $line =~ "Method Not Allowed" ]]; then
    

    (如果您使用正则表达式,请确保正则表达式运算符未被引用。)