Linux find exec command examples

I just wrote about how to use the Linux find command to find files by modification date, and I thought I'd follow that tutorial up with a quick example of how to find one or more files and then execute a command on those files. You do this with the Unix/Linux find command and the very powerful exec option.

A simple find exec example

For a quick and simple find/exec example, let's suppose you want to find all files named "foo" and then run an "ls -l" command on them. To do this you use the find command with the "exec" option, as shown here:

find . -type f -name "foo" -exec ls -l {} \;

Most of that command is readable, except for the obscure part at the end. Let's break it down:

  • 'find .' means look in the current directory and all subdirectories
  • '-type f' means only look for files, don't look at directories
  • '-name "foo"' means only look for files named foo
  • 'exec ls -l {}' means run the "ls -l" command on this set of files
  • The '\;' at the end of the command is an obscure syntax that is required by the find command when used with exec. (Frankly I don't know why it's needed, but it is.)

More find exec examples

Given that simple "find exec" example, let's take a look at a few more examples. Here's how you change all files beneath the current directory to have a mode of 644:

find . -type f -exec chmod 644 {} \;

Here's how you change all subdirectories to have a mode of 755:

find . -type d -exec chmod 755 {} \;

Note the use of "-type d" there to denote "directories".

You can also use this find/exec pattern to execute many more Unix and Linux commands on files you find, including the powerful and dangerous "rm" command.

I've written much more about the find command in my Linux find command examples on the devdaily.com website, so rather than repeat all of those, I'll just direct you there for more information.

I hope these examples of how to use find and exec have been helpful. As you can see, the find command is very powerful, and dangerous, so be productive, but be careful.

Valley Programming is currently a one-person business, owned and operated by Alvin Alexander. If you’re interested in anything you read here, feel free to contact me at “al” at (“@”) this website name (“valleyprogramming.com”), or at the phone number shown below. I’m just getting back to business here in November, 2021, and eventually I’ll get a contact form set up here, but until then, I hope that works.