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 -print0 | xargs -0 survives file names with spaces

Find
~/tips/tip-shell-find-print0-xargs-0

find . -name '*.tmp' -print0 | xargs -0 rm --

Passes file names between find and xargs safely, even with spaces or quotes in them.

find ... | xargs rm looks fine and works until someone saves a file called holiday photo.jpg. Then xargs sees two words.

By default xargs splits its input on whitespace and treats quotes and backslashes as special. File names can contain all of those. find -print0 separates results with a NUL byte instead of a newline, and xargs -0 reads NUL-separated input and leaves quotes and backslashes alone. A file name cannot contain NUL, so nothing is ambiguous.

find . -name '*.tmp' -print0 | xargs -0 rm --
find . -type f -print0 | xargs -0 -r ls -l

The -r (--no-run-if-empty) in the second line is GNU xargs: when find finds nothing, xargs does not run the command once with no arguments. Without it, a bare ls would list the current directory. That is a nasty surprise with some commands.

Caveat: -r is a GNU option. The xargs on macOS does not run an empty command by default and has its own set of flags, so check man xargs before you copy a line between Linux and Mac. And for a simple delete, find -delete or find -exec ... + avoids the pipe altogether.

Further reading: xargs(1) man page, GNU findutils manual, On this site: put -delete last in find, or it deletes more than you think, On this site: xargs -P runs commands in parallel, no GNU parallel needed

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