Some good answers here, but like the OP I found myself wanting, in a scripting context, all of:
- any response body returned by the server, regardless of the response status-code: some services will send error details e.g. in JSON form when the response is an error
- the HTTP response code
- the
curl
exit status code
This is difficult to achieve with a single curl
invocation and I was looking for a complete solution/example, since the required processing is complex.
I combined some other bash recipes on multiplexing stdout/stderr/return-code with some of the ideas here to arrive at the following example:
{
IFS= read -rd '' out
IFS= read -rd '' http_code
IFS= read -rd '' status
} < <({ out=$(curl -sSL -o /dev/stderr -w "%{http_code}" 'https://httpbin.org/json'); } 2>&1; printf '\0%s' "$out" "$?")
Then the results can be found in variables:
echo out $out
echo http_code $http_code
echo status $status
Results:
out { "slideshow": { "author": "Yours Truly", "date": "date of publication", "slides": [ { "title": "Wake up to WonderWidgets!", "type": "all" }, { "items": [ "Why <em>WonderWidgets</em> are great", "Who <em>buys</em> WonderWidgets" ], "title": "Overview", "type": "all" } ], "title": "Sample Slide Show" } }
http_code 200
status 0
The script works by multiplexing the output, HTTP response code and curl
exit status separated by null characters, then reading these back into the current shell/script. It can be tested with curl
requests that would return a >=400 response code but also produce output.
Note that without the -f
flag, curl
won't return non-zero error codes when the server returns an abnormal HTTP response code i.e. >=400, and with the -f
flag, server output is suppresses on error, making use of this flag for error-detection and processing unattractive.
Credits for the generic read
with IFS processing go to this answer: https://unix.stackexchange.com/a/430182/45479 .