Exec and Execdir
When built-in actions like -print and -delete are insufficient, the -exec family allows you to transform find into a powerful batch processing engine by passing matched files to external commands.
The -exec Action
The syntax for -exec requires specifying the command, placing {} where the filename should be injected, and terminating the statement with an escaped semicolon \;.
find /etc -type f -name "*.conf" -exec chmod 644 {} \;
How it Works
For every single file that matches, find spawns a brand new shell process, executes the command, and waits for it to finish. If find matches 10,000 files, it will spawn 10,000 chmod processes.
This is highly versatile but computationally expensive.
Batching with +
To mitigate the performance hit of spawning thousands of processes, you can terminate the -exec statement with + instead of \;.
This tells find to append all matching filenames as arguments to a single execution of the command (similar to how xargs works).
# Fast: Spawns a single process: chown root a.txt b.txt c.txt ...
find /etc -type f -name "*.conf" -exec chown root {} +
Note: You can only place {} at the very end of the command when using +.
The Security Flaw of -exec
Consider this command:
find /tmp/uploads -type f -name "*.jpg" -exec mv {} /var/www/images/ \;
There is a subtle race condition vulnerability here. What if, during the search, a malicious user deletes a directory inside /tmp/uploads and replaces it with a symlink pointing to /etc? The -exec command might unwittingly modify system files because it resolves the full absolute path from the root directory at execution time.
The Solution: -execdir
To solve this, modern find introduced -execdir.
Instead of executing the command from the directory where find was launched, -execdir temporarily cds into the directory containing the matched file, and executes the command using a safe relative path (./filename).
# Safer: Executes `mv ./file.jpg /var/www/images/` from inside the specific subfolder
find /tmp/uploads -type f -name "*.jpg" -execdir mv {} /var/www/images/ \;
In production automation scripts, always use -execdir instead of -exec when invoking commands that modify file permissions, ownership, or move/copy data.
Interactive Execution: -ok
If you are running a destructive command manually and want to be prompted for confirmation before every single execution, use -ok (or -okdir).
find /var/www -type f -name "wp-config-backup*.php" -ok rm {} \;
# Prompt: < rm ... ./wp-config-backup1.php > ? y