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: one tmpfiles.d line deletes old files from a folder on schedule

Linux
~/tips/tip-systemd-tmpfiles-age-cleanup

d /srv/scratch 0755 root root 14d

Removes files older than a set age from a directory every day, without cron.

Most servers have a folder that only grows: exports, scratch files, old dumps. Most people write a cron job with find -mtime for that. systemd already ships a cleaner that runs every day, and it takes one line of config.

systemd-tmpfiles reads .conf files in /etc/tmpfiles.d/. A d line creates a directory with the mode and owner you give, and the age field tells the daily cleanup what may go:

# /etc/tmpfiles.d/scratch.conf
# type path          mode user group age
d     /srv/scratch  0755 root root  14d

Files in /srv/scratch that are older than 14 days are deleted. The cleanup itself is systemd-tmpfiles-clean.timer, which upstream starts 15 minutes after boot and then once a day. You can trigger it by hand:

sudo systemd-tmpfiles --clean --dry-run
sudo systemd-tmpfiles --clean

--dry-run prints what it would do without touching anything. That option needs systemd 256 or newer, so on an older release you’d test on a copy instead. If the folder is already there and you don’t want tmpfiles to touch its mode or owner, the e type only cleans it.

The caveat is how it decides what is old. It looks at the modification time, the access time and (for files) the change time, and any recent one keeps the file alive. A file nobody changed but somebody read yesterday stays. The age field can take a prefix to limit that, such as mM:14d to look at the modification time only. My advice: point it at a folder that holds nothing but throwaway files, because it deletes without asking.

Further reading: tmpfiles.d(5) manual page, systemd-tmpfiles(8) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link