How to Execute a Command on Every File Found in Ubuntu (find -exec)

The Automation Pipeline

Finding files in Ubuntu Linux is only half the battle; usually, you need to actually do something with those files once you find them. If you need to find thousands of old log files and delete them, or locate hundreds of image files and change their permissions, manually typing the command for every single file is impossible. Instead of writing a complex bash script with a “for loop,” you can seamlessly integrate the action directly into the search engine itself.

Using the find Command with -exec

The Linux find command utilizes the -exec (execute) flag to run a secondary Linux command against every single file it discovers.

  1. Open your Terminal application (Ctrl + Alt + T) or log into your server via SSH.
  2. To search the /var/log/ directory for all files ending in .gz and automatically delete them, type the following command exactly:
  3. sudo find /var/log/ -name "*.gz" -exec rm {} \;
  4. Press Enter and provide your administrator password.

Understanding the Syntax

The -exec flag essentially opens a sub-shell. Following it, you type the standard Linux command you want to run (in this case, rm for remove). The curly braces {} act as a variable placeholder; for every file the search engine finds, it injects the absolute file path into those braces. Finally, you must terminate the execution block by typing a backslash followed by a semicolon \; so the bash shell knows where the internal command ends. Warning: Be extremely careful using -exec rm, as it will silently and permanently delete massive amounts of data without asking for confirmation.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.