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: printf %(…)T puts today's date in a name without calling date

Shell
~/tips/tip-shell-printf-v-date-builtin

printf -v stamp '%(%Y-%m-%d_%H%M)T' -1

Writes the current date into a shell variable using only the printf builtin.

Backup scripts love a date in the filename, and most of them start a separate date process just for that. Bash can do it by itself.

The printf builtin has a %(datefmt)T conversion. It formats a time with strftime-style codes. The argument is the number of seconds since the epoch, and the manual gives two special values: -1 is the current time and -2 is the time the shell was invoked. With no argument at all it acts as if -1 was given. Add -v and the result goes into a variable instead of the screen:

printf -v stamp '%(%Y-%m-%d_%H%M)T' -1
tar -czf "/mnt/user/appdata/backup-$stamp.tar.gz" /mnt/user/appdata/<app>

That gives a file name like backup-2026-11-28_1405.tar.gz. A plain date works the same way:

printf '%(%F)T
'

The -2 value is handy when every log line of one script run should share a timestamp, because it stays the same however long the script runs:

printf -v run_id '%(%Y%m%d-%H%M%S)T' -2
echo "run $run_id started"

It saves a process per call, which only matters in a loop that runs thousands of times, but I like that there is nothing to install or quote.

Check the shell first. This is a bash feature and older versions lack it, so it will not work in plain sh or dash. macOS also still ships bash 3.2 in /bin/bash, so run bash --version before you rely on it there.

Further reading: bash(1) manual page

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link