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 -ok asks before it runs a command on each file

Find
~/tips/tip-find-ok-confirm-each-file

find ~/Downloads -name '*.iso' -ok rm {} \;

Asks for a yes or no before find runs a command such as rm on each file.

find with -exec rm is fast, and it’s also a little scary when you’re not quite sure your pattern is right. There’s a polite twin of -exec that asks first, file by file.

find ~/Downloads -name '*.iso' -ok rm {} \;

-ok works like -exec, but for every match it prints the command it’s about to run, with the file name filled in, and waits for your answer. Type y and it runs. Anything else, or just Enter, and find skips that file and moves on. The prompt goes to stderr, so you still see it when you send the normal output somewhere else.

Where I’d use it: cleaning up a folder where most matches can go but a few should stay. Say you want to get rid of old installer images, except the one you keep for a VM on the server. With -ok you go through the list once, answer y or n per file, and nothing disappears without your say-so. There’s also -okdir, which does the same as -execdir: it runs the command from inside the folder of the file.

A few caveats. -ok only takes the \; ending, not +, so it’s one prompt and one command per file. That’s fine for twenty files and painful for two thousand, so for big sets I’d check the list with -print first and use -exec after. The command itself gets /dev/null as its input, so a program that wants to ask its own question, like rm -i, can’t read your answer. Let find do the asking.

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