Get the HTTP status code AND the content from curl


curl is an awesome tool for getting HTTP resources, but I recently needed to get the HTTP status code (200/404/etc) in addition to the content. The trick is to use both stdout and stderr:

TMPFILE=$(mktemp)
STATUSCODE=$(curl \
	-X GET \
	-H "accept: application/json" \
	--silent \
	--show-error \
	--output /dev/stderr \
	--write-out "%{http_code}" \
	"https://api.example.com/" \
	2> ${TMPFILE})

Date: 2019-06-28

Tags:  curl  http

Share: