简体   繁体   中英

curl to get response status code and evaluate

Trying to get status code for a curl post request and use if condition to check status code 200 or not

for ((i = 1; i <= $max; i++)); do
  id=$((id_range + $i))

  code= $(curl -s -w "%{http_code}" -o /dev/stderr  -X POST $URL -H "Authorization: Basic $AUTH" -H "Content-Type: application/json"  -H "Accept: application/json" -d '{
    "id": "'$id'",
    "name": "tom",    
    "status": "active",    
     }'
     )

    if [ "$code" = "200" ]
    then
      echo "Employee added : " $code
    else
      echo "Employee not added : " $code
    fi

  
done

But this didnt work for me, not getting the status code

if I dont go for status code curl request works

for ((i = 1; i <= $max; i++)); do
  id=$((id_range + $i))
  curl   -X POST $URL -H "Authorization: Basic $AUTH" -H "Content-Type: application/json"  -H 
  "Accept: application/json" -d '{
  "id": "'$id'",
  "name": "tom",    
  "status": "active",    
 }'

Any other better options to get the status code

Space — the final frontier. There's a blank after the = which should not be there:

code= $(curl -s -w "%{http_code}" ...)

Note that the shell is white-space sensitive in many places and variable assignment is one of them. The syntax is NAME=[VALUE] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM