The find command

The find command is very useful. It can search the entire file system for one or more files that you specify to look for. With the find command, not only are you able to locate files, but you can also perform actions on the files it finds like move, delete, rename …

# find PHP files from the current directory and move them to the home directory
find . -name "*.php" -exec mv {} ~ \;

# change the owner of all files in /usr/local/test directory
find /usr/local/test -exec chown dbunic {} \; 

# find java files that contain the "getSize" method
# -i ignore case
# -H print the filename for each match
find . -name "*.java" -exec grep -iH getSize {} \;

# find files from the /var directory modified within 15 days
find /var -mtime -15

# set permission 755 to the directories only (recursively from the current directory)
find . -type d -exec chmod 755 {} \;
find . -type d | xargs chmod 755

# set permission 644 to the files only (recursively from the current directory)
find . -type f -exec chmod 644 {} \;
find . -type f | xargs chmod 644

# delete files from the /usr/local/logs older then 7 days (note + in ctime parameter)
find /usr/local/logs -ctime +7 -exec rm {} \;

# delete files from the current directory modified within a day
find . -type f -mtime -1 -exec rm {} \;

# delete files in /tmp directory except jpg and flv files
find /tmp -not -name "*.jpg" -not -name "*.flv" -delete

As you can see, the find command is powerful. These examples are from my cookbook collected over the past few years. At the end, I will show how to delete old files and change file’s owner and group using tmpwatch and chown command.

# delete files from the /tmp directory older than 8 hours
tmpwatch -maf 8 /tmp

# change file's owner and group to all files from the /home/dbunic directory
chown -R dbunic.users /home/dbunic

The result is the same as with find command, but it looks simpler.

Leave a Comment