Friday, November 14, 2008

find - swiss army knife

There are some unix commands which can get lots of work done with very little effort. find most probably comes top of such list. I use find almost every other day to get following things done.

  • Delete files matching a pattern recursively
$ find /home/prasadvk/dev -name "*.core"

It will delete all files ending .core from directory /home/prasadvk/dev or subdirectories of it. Many novices try command -

$ rm -rf *.core

This command doesn't do the expected thing. Primarily shell expands *.core to a list of files in the current directory and *.core never seen by rm command. Essentialy this command removes .core files from only current directory and not sub directories.

  • Delete files older than 15 days
$ find . -mtime +15 -type f -exec rm -f {} \;

It will delete all files from current directory or subdirectory which have modification time older than 15 days. -exec allows you to execute any command of your choice on each file outputted by find. The wierd syntax '{}\;' refers to the filename substitution. The flag "-type f" ensures only regular files will be deleted. Refer to man to explore more options to meet your needs.

  • Find the file with inode 1024.
$ find -inum 1024

On linux, it finds file with inode 1024.

This is only a small list and possible uses can make a very hefty list. Feel free to add most common uses of find to this post.

No comments: