brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: curl --fail-with-body keeps the error page and still returns exit code 22

Curl
~/tips/tip-curl-fail-with-body

|| { echo "request failed: $resp" >&2; exit 1; }

Makes curl exit with code 22 on an HTTP error but still prints the server's error message.

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

More Curl tips curl --trace-ascii – https://example.com/ Retry-After: 120 curl -fsS --fail-early \ url = "https://example.com/data/latest.json" curl -4 -s -o /dev/null -w '%{remote_ip} %{http_code}\n' https://example.com/ All Curl tips (71) All topics

Link