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

\r\nHTTP プロトコルでは、ヘッダー行は <CR><LF> ( UNIX 表記では復帰改行) で終わる必要があります。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

両方とも同じ行にあります。

関連情報