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 -execdir runs a command inside the folder where each file lives

Find
~/tips/tip-find-execdir-run-in-folder

find /mnt/user/downloads -name '*.zip' -execdir unzip -n {} \;

Runs a command from the folder of each matched file, so output lands next to it.

Some commands care about the folder they run in. Unpacking is the classic case: unzip an archive from your home folder and the files land in your home folder, far away from the zip they came from.

-exec runs every command from the folder where you started find. -execdir first moves into the folder that holds the match and passes the command ./name instead of the full path:

find /mnt/user/downloads -name '*.zip' -execdir unzip -n {} \;

Each zip file gets unpacked next to itself, however deep it sits in the tree. The -n tells unzip never to overwrite a file that already exists, so running the line a second time skips what is already there instead of asking you about every file.

The + form works too. find then collects the matches per folder, and each run of the command only gets files from a single directory, which is handy for tools that want to process a whole folder in one go.

The man page calls -execdir the more secure choice, since it avoids race conditions while paths are resolved. It also comes with one warning: your PATH must not contain . or empty entries. Otherwise someone could drop a file with the right name into a folder and find would happily run it. With a normal PATH you will never notice, but if you once added . for convenience, this is a good reason to take it out again.

Further reading: find(1) manual page, unzip(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