
컬 명령의 값을 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
컬이 HTTP/1.1 401 Unauthorized를 반환하기 위해 의도적으로 잘못된 비밀번호를 전달하고 있습니다. 잘못된 자격 증명이 서버로 전송되었는지 확인하는 기능이 필요합니다.
이상한 점은 컬 명령의 출력을 저장할 때 즉
HTTP_STATUS=$(curl -IL --silent $username:$password@$IP_addr | grep HTTP | tee $curr/test.txt)
티가 있는 파일에는 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\n
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
둘 다 같은 줄에 있습니다.