DEV Community

Eduardo Issao Ito
Eduardo Issao Ito

Posted on • Edited on

3 4

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)

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay