sandra_henrystocker
Unix Dweeb

Unix How-To: Making Better Use of Find

Analysis
Sep 22, 20103 mins

Abstract circular bokeh white light gray sliver colors
Credit: Nongnuch_L / Shutterstock

The find command is not just useful for locating files, but also for doing things with the files once it finds them. You can find files based on numerous criteria — their names, their owners, their size, etc. — and you can then perform some operation on the files from simply listing them to changing permissions or analyzing their contents. You can also make the operation that you specify to occur only if you confirm that you want it to happen after you are prompted. Let’s see how this works.

The most standard use of the find command seeks to locate files based on some simple parameter such as their names, owners, size, etc.

find . -name *.sh
find / -user jdoe
find . -mtime -1

You can also pass the list of found files to some other utility using find’s -exec clause, xargs or some other tool.

find . -name *.sh -exec chmod g+x {} ;
find / -user jdoe >> /tmp/jdoe.files
find . -mtime -1 | xargs chmod g+r

The {} specification in the first command is replaced for each iteration of the chmod command by the found file’s name.

You can, however, elect to take action on each found file on a case by case basis. Using the -ok parameter, the find command will take the action specific (the “head -1” command in the example below) only if you confirm by typing “y” or “Y” at the prompt.

$ find . -type f -ok head -1 {} ;
< head ... ./dir1/file1 >?   n
< head ... ./dir1/file2 >?   n
< head ... ./dir2/file1 >?   y
This file contains a listing of all participants in the August 2010 retreat.  Note that all

In other words, the -ok option takes the place of the exec command and adds the behavior of prompting the user for a response of whether to proceed with the action specified. This can be useful if you, for example, want to avoid counting lines or grepping on the contents of binary files.

sandra_henrystocker

Sandra Henry-Stocker was a programmer, Linux systems administrator, security engineer and Linux journalist for most of her 30-year career. She describes herself as "USL" (Unix as a second language) but remembers enough English to write books and buy groceries. She lives in the mountains in Virginia where, when not working with or writing about Unix, she's chasing the bears away from her bird feeders. Tune into her 2-Minute Linux video tutorials and take command of your command line.

More from this author