How to Find and Execute Commands on Files in Ubuntu (find -exec)

The Automation Engine

In Ubuntu Linux, locating specific files is only half the battle. Often, system administrators need to find a massive list of files and immediately perform an action on them—such as changing permissions on a thousand log files or moving specific backups to a new directory. Piping the output of find into xargs is common, but find possesses a built-in, highly secure automation engine that allows it to execute commands directly on the files it discovers without risking shell expansion errors.

Using the find Command with -exec

The Linux find command utilizes the -exec flag to run a specified binary against every single file that matches the search criteria.

  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 immediately change their permissions to read-only (644), type the following command exactly:
  3. sudo find /var/log/ -name "*.gz" -exec chmod 644 {} \;
  4. Press Enter and provide your administrator password.

Command Execution Syntax

The syntax of -exec is strict. The chmod 644 portion is the command you wish to run. The curly braces {} act as a variable placeholder; the find command will automatically inject the absolute path of the discovered file into that exact spot. Finally, the command must be terminated with an escaped semicolon \; to signal to the bash shell where the -exec sequence ends. This built-in loop allows for incredibly rapid, automated mass-modifications across complex directory trees.

Get the best tech tips delivered straight to your inbox.

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