How to use find -exec Command Option in Linux

The find -exec option lets you run commands on files that match your search criteria, turning find into a batch processing engine. Whether you’re backing up photos spread across nested directories, compressing old logs older than 30 days, or adding watermarks to hundreds of images at once, find -exec handles repetitive file operations without writing custom loops.

This guide walks through the core syntax, shows how to install findutils on minimal systems, and delivers practical examples covering backups, renaming, format conversion, remote syncing, and automated reporting. You will learn how to structure find -exec commands for safe batch operations, combine them with shell scripts for complex transformations, and integrate them into cron jobs for scheduled maintenance. Pair this with our chmod command guide when you need to modify permissions in bulk, or our mkdir examples for creating directory structures based on file patterns.

Understand the find -exec Command

What find -exec Does

If find -exec is new to you, think of it as a command-line automation assistant that scouts for files matching your criteria and then runs a specific action on each one. The find command locates files based on name patterns, modification times, sizes, or permissions. The -exec option extends that by letting you process each match immediately without piping to xargs or writing a loop.

Syntax Breakdown

The basic structure combines find’s search capabilities with command execution:

find [path] [expression] -exec [command] {} \;
  • [path]: Where to start searching. Use /var/log to scan log directories, . for the current directory, or ~ for your home folder.
  • [expression]: What to search for. Examples: -name "*.txt" finds text files, -mtime +30 finds files older than 30 days, -size +100M finds files larger than 100 megabytes.
  • -exec [command]: The action to perform on each match. Use ls -lh to list details, cp to copy, gzip to compress, or any command you would normally run manually.
  • {}: Placeholder replaced by each file’s full path. Every time find matches a file, it substitutes the actual filename here.
  • \;: Marks the end of the -exec command. The backslash escapes the semicolon so your shell does not interpret it prematurely. Some users prefer \+ instead, which batches multiple files into a single command invocation for better performance.

Simple Example First

At its simplest, find -exec runs a command on every match. To list detailed information for all PDF files in your Documents folder:

find ~/Documents -name "*.pdf" -exec ls -lh {} \;

This searches ~/Documents, finds every file ending in .pdf, and runs ls -lh on each one to show the size, permissions, and modification date. You see one line of output per PDF.

Common find -exec Patterns by Task

The following table organizes typical find -exec scenarios by what you want to accomplish:

TaskExpression & CommandWhat It Does
Back up files-name "*.jpg" -exec cp {} {}.backup \;Creates a .backup copy of every .jpg file found
Delete old logs-name "*.log" -mtime +30 -exec rm {} \;Removes log files older than 30 days
Compress files-name "*.txt" -exec gzip {} \;Compresses each text file with gzip
Change permissions-type f -name "*.sh" -exec chmod +x {} \;Makes all shell scripts executable
Move files-type f -name "*.tmp" -execdir sh -c 'mkdir -p ./archive && mv "$1" ./archive/' _ {} \;Moves temporary files into an archive subdirectory created alongside each match
Display file details-name "*.conf" -exec ls -lh {} \;Shows size and permissions for config files
Rename files-name "*.html" -exec sh -c 'mv "$1" "${1%.html}.htm"' _ {} \;Changes .html extensions to .htm
Search file contents-name "*.cfg" -exec grep -H "error" {} \;Finds lines containing “error” in config files

Use \; when you need one command execution per file (safer for operations that modify files). Use \+ when processing many files with read-only commands like ls or grep to reduce overhead.

Check and Install find on Linux

Most Linux distributions ship with GNU findutils pre-installed, but minimal containers, Alpine-based images, or custom rescue environments might not include it. Verify the version first before relying on advanced options.

Check if find is Installed

Run this command to confirm find is available and check its version:

find --version

If you see version output starting with “GNU findutils,” you have the full toolset. If the command is not found, install the package for your distribution.

Install find on Linux Distributions

Ubuntu and Debian-based distributions:

sudo apt install findutils

Fedora, RHEL, Rocky Linux, and AlmaLinux:

sudo dnf install findutils

Arch Linux and Manjaro:

sudo pacman -S findutils

openSUSE:

sudo zypper install findutils

On Alpine Linux and other minimal distributions, the default BusyBox find lacks some GNU extensions. Install the full GNU findutils package if you need features like -exec {} \+ or advanced time expressions.

Practical Examples Using the find -exec Command Option

Backing Up Files with find -exec

When you need to back up specific file types before making changes, find -exec lets you create copies without manually selecting each file. This is useful before running batch updates or testing new scripts that modify originals.

To find and create backups of all .jpg files in the /pictures directory:

find /pictures -type f -name "*.jpg" -exec cp {} {}.backup \;

This command locates each .jpg file and creates a backup by copying each file to a new file with the .backup extension.

Renaming File Extensions Using find -exec

Bulk renaming file extensions is common when migrating projects or standardizing naming conventions across a codebase. The shell’s parameter expansion feature ${1%.html}.htm strips the old extension and adds the new one.

To change the extension of all .html files to .htm in the /web directory:

find /web -type f -name "*.html" -exec sh -c 'mv "$1" "${1%.html}.htm"' _ {} \;

This command renames each .html file, replacing the extension with .htm.

Converting Image Formats with find -exec

When you need to convert image formats in bulk for web optimization or compatibility, find -exec can process entire directories at once. This example requires ImageMagick to be installed (available in most distribution repositories).

To convert all .png images to .jpg in the /images directory:

find /images -type f -name "*.png" -exec sh -c 'convert "$1" "${1%.png}.jpg"' _ {} \;

This wraps convert (part of ImageMagick) in a tiny shell so each .png gains a matching .jpg copy like photo.jpg while leaving the original PNGs untouched.

Compressing Log Files: A find -exec Approach

System logs accumulate rapidly and consume disk space. Compressing older logs preserves history while freeing capacity. The -mtime +7 flag targets files modified more than 7 days ago, ensuring recent logs stay accessible for active troubleshooting.

To find and compress all .log files older than 7 days in /var/log:

find /var/log -type f -name "*.log" -mtime +7 -exec gzip {} \;

This command selects .log files older than 7 days and compresses them using gzip.

Removing Empty Directories with find -exec

Empty directories clutter file systems and complicate backups. The -type d -empty expression isolates directories containing no files or subdirectories, and rmdir removes them safely without touching non-empty folders.

To find and remove all empty directories in the /data directory:

find /data -type d -empty -exec rmdir {} \;

This command identifies empty directories within /data and removes them, streamlining the file system. Use our mkdir command guide when you need to recreate directory structures or understand directory creation patterns.

Advanced Use Cases for the find -exec Option

This section delves into more complex scenarios, addressing commonly asked questions and challenging tasks that can be efficiently handled using the find command with the -exec option. These examples are tailored for specific, advanced use cases, ensuring the commands are practical, relevant, and functional.

Syncing Files to Remote Servers: Advanced find -exec Usage

When you need to back up specific file types to a remote server, combining find with rsync provides efficient incremental transfers. This pattern works well in cron jobs for automated off-site backups.

The following pipeline prints each match relative to /local/docs and hands the entire list to rsync in one invocation, so the directory structure stays intact and files with identical names do not overwrite each other:

find /local/docs -type f -name "*.pdf" -printf '%P\0' | rsync -av --from0 --files-from=- /local/docs/ user@remote_server:/remote/docs/

find uses -printf '%P\0' to emit a null-terminated list of PDFs relative to /local/docs. rsync reads that list with --from0 and --files-from=-, preserves the directory hierarchy under /local/docs, and transfers only the files that changed since the last run.

Date Stamping File Names: A find -exec Technique

Adding timestamps to filenames helps track versions and maintain chronological organization. The $(date +%Y%m%d) command inserts the current date in YYYYMMDD format, while dirname and basename preserve the original directory structure.

To add a current date stamp to the filenames of all .csv files in /data/reports:

find /data/reports -type f -name "*.csv" -exec sh -c 'mv "$1" "$(dirname "$1")/$(date +%Y%m%d)-$(basename "$1")"' _ {} \;

This command locates .csv files and renames each by prefixing the current date, enhancing file organization and version control.

Generating Large File Reports via find -exec

Monitoring disk usage proactively prevents capacity emergencies. This command identifies files consuming significant space and sends a detailed report to administrators, useful for scheduled capacity audits.

To find files larger than 100MB in /home and email a report:

find /home -type f -size +100M -exec ls -lh {} \; | mail -s "Large Files Report" admin@example.com

This command identifies files over 100MB, lists their details, and sends this information via email, assisting in capacity management and monitoring.

Automated Image Watermarking with find -exec

Protecting image copyrights at scale requires batch watermarking. This example uses ImageMagick’s composite tool to overlay a watermark at 30% opacity in the southeast corner of each image.

To add a watermark to all .jpg images in /images/gallery:

find /images/gallery -type f -name "*.jpg" -exec composite -dissolve 30% -gravity southeast watermark.png {} {} \;

This uses the composite command (part of ImageMagick) to overlay a watermark image on each .jpg file, crucial for copyright protection and branding. Install ImageMagick via your package manager if the composite command is not available.

Directory Creation Based on File Names Using find -exec

Organizing media libraries often requires creating folders matching file names. The basename command extracts the filename without extension, and mkdir -p creates the directory if it does not already exist.

To create directories based on the names of .mp4 files in /videos:

find /videos -type f -name "*.mp4" -exec sh -c 'mkdir -p "/archive/$(basename "$1" .mp4)"' _ {} \;

This pattern passes each matched path to the shell as $1, so basename safely strips the .mp4 extension even when filenames contain spaces, and mkdir -p builds the matching directory under /archive. For more directory management tips, see our mkdir command guide.

Conclusion

The find -exec command transforms file searches into automated batch operations, handling everything from simple backups to complex multi-step transformations without custom scripts. By understanding the placeholder syntax {}, choosing between \; for individual execution and \+ for batched performance, and combining find expressions with shell commands via sh -c, you can confidently process thousands of files based on name patterns, modification times, or sizes while maintaining precise control over each operation.

Leave a Comment