Cork Kochi
Cork Kochi

Reputation: 1891

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

Upvotes: 0

Views: 212

Answers (1)

Jens
Jens

Reputation: 72639

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].

Upvotes: 2

Related Questions