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 -depth lists a folder's contents before the folder itself

Find
~/tips/tip-find-depth-contents-first

find /srv/data -depth -print

Changes find's order so files come before their folder, which some copy and delete jobs need.

find normally prints a folder first and then what’s inside it. For most searches, the order doesn’t matter. For tools that create or remove things in that order, it does.

find /srv/data -depth -print

With -depth, find handles the contents of every folder before the folder itself. For a small tree that prints /t/a/b/two.txt, then /t/a/b, and /t/a comes last.

I see two cases where that matters. Removing things: a folder can only be removed once it’s empty, so the files have to go first. -delete switches -depth on by itself for that reason. And copying with cpio: if a read-only folder is created before its files, the files can’t be written into it. That’s why the classic way to copy a tree with cpio is:

cd /srv/data && find . -depth -print0 | cpio -0pdm /mnt/copy

The catch is -prune. Pruning skips a folder before going into it, but with -depth find has already been inside, so -prune does nothing. If you combine the two, the folder you wanted to skip is searched anyway. That’s also why -delete and -prune don’t work together.

Further reading: find(1) manual page, GNU findutils manual

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 -xdev -samefile /srv/downloads/movie.mkv find / -xdev -user olduser -ls 2>/dev/null All Find tips (46) All topics

Link