I like curl -f in scripts, but it has one annoying side effect: when the server says no, you never see why. --fail-with-body fixes that.
With -f (--fail), curl returns error 22 for any HTTP status of 400 or higher and prints no body at all. The server often explains the problem in that body, a JSON error from an API for example. --fail-with-body does the same check but still outputs or saves the content:
resp=$(curl --fail-with-body -sS https://example.com/api/items) \
|| { echo "request failed: $resp" >&2; exit 1; }
If the call fails, the script prints the server’s own message together with the failure, instead of a bare exit code. In the success case $resp holds the normal response. The -sS pair hides the progress meter but still shows curl’s own errors.
Some details from the manual:
- It was added in curl 7.76.0, so very old builds do not have it.
- It is mutually exclusive with
--fail. Pick one of them. - The exit code is the same 22 as with
--fail, so existing error handling keeps working.
One caveat. The manual says about --fail that it is not fail-safe and that some non-success codes can slip through, especially 401 and 407 during authentication. I would not assume the sibling option is any different, so for anything important I also check the status code with -w '%{http_code}'. And remember that without either option curl treats a 404 or 500 as a successful transfer, because it did get an answer.
Further reading: curl man page: –fail-with-body