在 if 語句中使用變數空白但不使用 echo

在 if 語句中使用變數空白但不使用 echo

我正在嘗試將curl 命令中的值保存到bash 腳本中的變數中。

腳本看起來像這樣

#!/bin/bash

curr=$(pwd)
IP_addr="192.168.0.102"
username="root"
password="pass"

HTTP_STATUS=$(curl -IL --silent $username:$password@$IP_addr | grep HTTP)
echo
echo "echo the variable works!"
echo $HTTP_STATUS
isOK=$(echo $HTTP_STATUS)
status="HTTP/1.1 401 Unauthorized"

echo

if [[ $HTTP_STATUS == $status ]]; then
    echo "The same the same!"
else
    echo "$isOK is not the same as $status"
fi

echo

if [ "$status" == "$isOK" ]
then
    echo "The same the same!"
else
    echo "$isOK is not the same as $status"
fi

我故意傳遞錯誤的密碼,以便curl返回HTTP/1.1 401 Unauthorized。我想要一個函數來檢查是否將錯誤的憑證傳送到伺服器。

奇怪的是,當我保存curl命令的輸出時,即

HTTP_STATUS=$(curl -IL --silent $username:$password@$IP_addr | grep HTTP | tee $curr/test.txt)

對於帶有 tee 的文件,我將其列印在文件 HTTP/1.1 401 Unauthorized 中。但是如果我刪除 tee 命令,即

HTTP_STATUS=$(curl -IL --silent $username:$password@$IP_addr | grep HTTP)

並執行我在終端中列印後得到的腳本

./test.sh 
echo the variable works!
HTTP/1.1 401 Unauthorized

is not the same as HTTP/1.1 401 Unauthorized

is not the same as HTTP/1.1 401 Unauthorized

我也嘗試了以下但結果相同

HTTP_STATUS=`curl -IL --silent $username:$password@$IP_addr | grep HTTP`

當我在 if 語句中進行檢查時,變數 HTTP_STATUS 似乎為空。這怎麼可能? 為什麼使用 tee 和 echo 變數將命令的輸出儲存到檔案中,但在 if 語句中使用變數時卻不起作用?

此致

答案1

HTTP 協定要求標頭行以 <CR><LF>(回車符和換行符,\r\nUNIX 表示法)結尾。要查看curl實際返回的內容,您可以嘗試:

curl -IL --silent $username:$password@$IP_addr | grep HTTP | cat -v

在 UNIX 中,<LF> 終止文字行,<CR> 只是一個普通字符,沒有特殊意義。後續訊息中明顯缺失的$isOK原因是尾隨 <CR>,它將遊標移回行首。詳細來說,線路

echo "$isOK is not the same as $status"

寫出

HTTP/1.1 401 Unauthorized<CR>
 is not the same as HTTP/1.1 401 Unauthorized

兩者在同一條線上。

相關內容