DEV Community

Eduardo Issao Ito
Eduardo Issao Ito

Posted on • Updated on

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)