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 with filename_effective prints the name it really saved

Curl
~/tips/tip-curl-filename-effective

file=$(curl -fsSLOJ -w '%{filename_effective}' "https://example.com/download?id=4812")

Find out which file name curl chose, so the next step in a script can use it.

With -O or -OJ curl picks the file name itself, from the URL or from the server. The write-out variable %{filename_effective} tells you what it picked.

Print the name after the download is done:

file=$(curl -fsSLOJ -w '%{filename_effective}' "https://example.com/download?id=4812")
echo "saved as $file"

With -J the name comes from the Content-Disposition header, which you cannot know beforehand. Capturing it means the next line of the script can unpack, checksum or move the exact file, instead of guessing with ls -t | head -1.

It also shows the effect of --output-dir and of no-clobber numbering, so you see downloads/report.pdf.1 when that is what happened.

I keep -s in these commands so nothing else lands on standard output except that name. The variable is only filled when curl actually writes to a file. If you send the body to standard output, there is no file name to report, and you get an empty string. Also be careful with names a server sends: curl strips directory parts from them, but a name with spaces or odd characters still needs quotes in the rest of your script.

Further reading: curl man page, everything curl: write out

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