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 --remove-on-error deletes the half-written file after a failure

Curl
~/tips/tip-curl-remove-on-error

curl --fail --remove-on-error -o /mnt/user/appdata/<app>/list.txt https://example.com/list.txt

Removes the output file when a curl transfer fails, so no half-downloaded file is left to use.

A failed download that leaves a broken file behind is worse than no file, because the next step in the script may happily use it. --remove-on-error cleans up after curl itself.

The manual describes it in one line: if curl returns an error while saving output to a local file, the output file is removed. This is meant to prevent a partial file after a failed transfer. A typical use:

curl --fail --remove-on-error -o /mnt/user/appdata/<app>/list.txt https://example.com/list.txt

If the connection drops halfway, or the server returns an error, list.txt is gone instead of cut off. The next line of the script can then check [ -f list.txt ] and know that the file is either complete or missing.

Notice that I added --fail. By default curl does not treat HTTP status codes as errors, so a 404 page would be saved as list.txt and curl would call that a success. With --fail or --fail-with-body, a status of 400 or higher counts as an error, and then --remove-on-error has something to react to.

Two limits from the manual. The option has no effect if the output is not a regular file, so output to a terminal, a pipe or /dev/null is untouched. And it cannot be combined with --continue-at (-C), because resuming needs the partial file to stay. If you want resumable downloads, keep the partial data and verify the file afterwards.

It does not replace a checksum. A transfer that curl considers finished can still hold the wrong content, and I would verify files that matter, with the hash from the download page, before using them.

A neighbouring option, --skip-existing, does the opposite job and skips a download when the file is already there. Using both needs care, because one keeps files that the other would have deleted.

Further reading: curl man page: –remove-on-error

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