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: mktemp --suffix gives a temp file the extension a tool expects

Shell
~/tips/tip-mktemp-suffix

f=$(mktemp --suffix=.json)

Create a unique temporary file that ends in a chosen extension

Some tools decide what to do from the file extension, and a temp file called tmp.k3Jd9x doesn’t give them any hint.

GNU mktemp can add the extension for you:

f=$(mktemp --suffix=.json)
curl -s https://example.com/data > "$f"
jq . "$f"
rm "$f"

This creates an empty file such as /tmp/tmp.4fQz8Rk1aB.json and prints its name. The random part keeps the name unique and hard to guess, so you avoid the clashes and symlink tricks that come with a fixed name like /tmp/data.json.

For a directory, use mktemp -d. To control the random part, give a template with at least three X characters: mktemp /tmp/report.XXXXXX.csv also works and ends in .csv.

A caveat: --suffix is a GNU option. The mktemp on macOS is the BSD version and doesn’t know it, but the template form mktemp /tmp/name.XXXXXX works on both, only without the extension after the random part. Remove the file when you are done, or use a trap in a script.

Further reading: mktemp(1) man page

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project shopt globskipdots echo $EPOCHSECONDS docker compose logs --tail 50 web # now at the top of a clean screen All Shell tips (78) All topics

Link