DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Administering filesystems

Executing commands based on find output

You can execute a specific shell command on the files that find locates using the -exec option. The most common use of -exec is to locate a group of files and then remove them.

For example, to find all the core files in the /usr filesystem that have not been accessed in seven days and remove them, enter:

find /usr -name core -atime +7 -exec rm "{}" \;

As another example, when you retire a user, use find to locate all the files owned by that user, back them up, and then remove them from the system. To do this, enter:

find / -user edwarda -print | cpio -ovBc > /dev/rfd0
find / -user edwarda -exec rm "{}" \;

The first command locates all the files owned by user edwarda and copies the files to a floppy disk archive. The second command locates the files and then removes them. For more information on copying files to an archive, see cpio(1).

To specify that find prompt you with the command line that find generates before executing the shell command on each file, use -ok in place of -exec:

find / -user edwarda -ok rm "{}" \;

In this case, find prompts you with:

   <rm ... /u/edwarda/billboard >?
To execute the command (in this case, rm), enter y. If you enter any character other than ``y'', the command is not executed.

Another common use of find with the -exec option is to locate all the files that belong to a particular group and change them. For example, if a user changes groups, you can use find to locate and change all their files to the new group:

find / -user edwarda -exec chgrp pubs "{}" \;

You can use find to change the owner of a group of files. For example, if you retire a user and you want to transfer ownership of their files to another user, use this command:

find / -user edwarda -exec chown earnestc "{}" \;

Using this construction to execute a command on a large group of files can be very slow because the -exec option forks a separate process for each file in the list. A more efficient method for doing this is to use xargs(1) in place of -exec. The xargs command forks fewer processes to execute the command on the entire group of files.


NOTE: Improper use of find with the xargs command can compromise system security. For this reason, root should not use find with xargs; use the -exec option to find instead.

The following example illustrates how to use the xargs construction with find:

find / -user edwarda -print | xargs chown earnestc

This command accomplishes the same thing as the previous example, only much more efficiently.


NOTE: If the syntax for the command that you want to execute with xargs deviates from the standard order (command options arguments), you must use -exec.


Next topic: Monitoring files and directories that grow
Previous topic: Finding temporary files

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 22 April 2004