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 -exec sh -c lets each file go through a small script

Find
~/tips/tip-find-exec-sh-c

find . -name '*.txt' -exec sh -c 'for f; do cp -- "$f" "${f%.txt}.bak"; done' sh {} +

Runs a few commands per file from find, with the file name passed safely.

-exec runs one command. When you need two steps, or a bit of string handling like changing the extension, I’d hand the files to a tiny script instead.

find . -name '*.txt' -exec sh -c 'for f; do cp -- "$f" "${f%.txt}.bak"; done' sh {} +

The script between single quotes is the program. The sh after it fills $0, the name the script runs under, and then find puts the file names, which the script sees as $1, $2 and so on. for f; loops over all of them. ${f%.txt} strips the extension, so notes.txt gets a copy called notes.bak. Because of the +, one sh process handles a whole batch of files.

The tempting shortcut is putting {} inside the quotes, like sh -c 'cp {} {}.bak'. That pastes the file name into the code, and a name with a quote, a semicolon or $(...) in it then runs as a command. Passing names as arguments avoids that completely.

The extra sh is easy to forget. Leave it out and the first file becomes $0, and the loop silently skips it. Test with echo in place of the real command until the output looks right.

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/data -depth -print find /srv -xdev -samefile /srv/downloads/movie.mkv All Find tips (46) All topics

Link