Use --fail-with-body
. This will cause curl
to exit with status code 22 when response code is >=400.
Note though that this flag is brand new (as of 2021/02/15), and was added in version 7.76.0, which postdates @rampion's answer. Thus it might not be available on your system.
https://curl.se/docs/manpage.html
--fail-with-body
(HTTP) Return an error on server errors where the HTTP response code
is 400 or greater). In normal cases when an HTTP server fails to
deliver a document, it returns an HTML document stating so (which
often also describes why and more). This flag will still allow curl to
outputting and save that content but also to return error 22.
This is an alternative option to -f, --fail which makes curl fail for
the same circumstances but without saving the content.
See also -f, --fail. Added in 7.76.0.
-f, --fail
(HTTP) Fail silently (no output at all) on server errors. This is
mostly done to enable scripts etc to better deal with failed attempts.
In normal cases when an HTTP server fails to deliver a document, it
returns an HTML document stating so (which often also describes why
and more). This flag will prevent curl from outputting that and return
error 22.
This method is not fail-safe and there are occasions where
non-successful response codes will slip through, especially when
authentication is involved (response codes 401 and 407).
See also --fail-with-body.