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: put -delete last in find, or it deletes more than you think

Find
~/tips/tip-shell-find-delete-order

find . -name '*.tmp' -delete

Deletes the files that match your tests, as long as -delete comes last in the command.

find reads its arguments left to right, like a little program. Put -delete in the wrong spot and you have written a different program.

Each test and action is evaluated in order. -delete is an action that removes the file, and it also turns on depth-first processing. Tests placed after it never get a say, because the file is already gone.

# right: only *.tmp files are deleted
find . -name '*.tmp' -delete

# wrong: deletes everything under the current directory
find . -delete -name '*.tmp'

The second command does not fail. It happily removes the lot. The find manual warns about this and tells you to put -delete last. The habit I would build is simple: first run the same command with -print instead of -delete, read the list, then swap the word.

Caveats. -delete is a GNU and BSD extension, not POSIX, though both the Linux and macOS versions have it. It also works on directories, but only empty ones. If you want a confirmation for each file, -ok rm {} \; asks before every deletion.

Same logic applies to -exec: find . -exec rm {} + -name x runs the rm on everything too.

Further reading: GNU findutils manual, On this site: find -print0 | xargs -0 survives file names with spaces, On this site: preview what git clean will delete with -n

More Find tips find / -maxdepth 1 -fstype proc find /backup -name '*.gz' ! -exec gzip -t {} \; -print 2>/dev/null find /srv/downloads -type f -size +100M -size -1G -exec ls -lh {} + find /srv/data -depth -print find /srv -xdev -samefile /srv/downloads/movie.mkv All Find tips (46) All topics

Link