Logo

dev-resources.site

for different kinds of informations.

Getting http status in curl

Published at
5/24/2022
Categories
bash
curl
Author
Eduardo Issao Ito
Categories
2 categories in total
bash
open
curl
open
Getting http status in curl

How to get the http status code of curl in a script?


my_curl() {
  Red='\033[0;31m'
  Green='\033[0;32m'
  Color_Off='\033[0m'

  TEMP_FILE=$( mktemp )
  trap "rm -f $TEMP_FILE" EXIT
  curl -w "\n%{http_code}" -s "$@" > ${TEMP_FILE}
  body=$(cat ${TEMP_FILE} | sed '$d')
  status=$(cat ${TEMP_FILE} | sed -n '$p')

  if [[ $status = 2* ]]; then
    Color=$Green
  else
    Color=$Red
  fi

  echo -e "${Color}Status: $status${Color_Off}"
  echo $body
}

my_curl -X GET http://jservice.io/api/random

Featured ones: