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: find -print -quit stops searching after the first match

Find
~/tips/tip-find-print-quit-first-match

find /mnt/user -name 'docker-compose.yml' -print -quit

Makes find stop at the first matching file instead of searching the whole folder tree.

Sometimes I don’t need every match, I just need to know there is one. find doesn’t care: it walks the whole tree anyway, and on a big media share with a few hundred thousand files that takes a while. GNU find has had an action for this since 2004.

find /mnt/user -name 'docker-compose.yml' -print -quit

-quit makes find exit right away. Because find works through the expression from left to right, it only gets to -quit for a file that passed the tests and was printed, so you get exactly one path and find stops walking. Exit code 0 means no errors occurred, it doesn’t say whether something was found, so check the output instead.

That makes it a cheap test in a script. Say you only want to start a cleanup job when old compressed logs exist at all:

if [ -n "$(find /var/log -name '*.gz' -mtime +30 -print -quit)" ]; then
  echo "old logs found"
fi

The test stops at the first old .gz file instead of listing all of them.

The caveat is the order. Put -quit before the tests and find quits on the very first thing it looks at, which is the starting folder, and you get nothing. Also, “first” means the first file find happens to reach, in the order the filesystem hands out directory entries. That’s not necessarily the newest or the biggest one. If you need one of those, you still need the whole list and a sort.

Further reading: find(1) manual page

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