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 -w %{onerror} prints a message only when the request failed

Curl
~/tips/tip-curl-write-out-onerror

curl -s -o /dev/null \

Stay quiet on success and print the exit code and error text on failure.

Cron jobs should be silent when things work and say something useful when they do not. %{onerror} does exactly that in a curl format string.

Everything after %{onerror} is only printed when the transfer returned a non zero exit code:

curl -s -o /dev/null \
  -w '%{onerror}curl failed: %{exitcode} %{errormsg}\n' \
  https://example.com/health

On success nothing appears. When the server is down you get a line like curl failed: 7 Failed to connect to example.com port 443. Since cron mails anything a job prints, that turns into an alert with the reason in it, and no wrapper script is needed.

Text before %{onerror} is always printed, so you can log a status for every run and add the error details only when something broke.

I find this cleaner than checking $? in a wrapper. Remember that an HTTP 404 or 500 is not a curl error by default. The transfer worked; the server just said no. Add -f if those status codes should count as failures too. %{onerror} needs curl 7.75, and %{errormsg} and %{exitcode} arrived in 7.75 as well, so this does not work on very old systems.

Further reading: curl man page, curl exit codes

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