Sunday, February 6, 2011

Searching filesystem from command line

 There are several commands available on the command line to locate files and folders on the file system. This article reviews three of them, viz whereis ,locate. find.

1) whereis
This command can search for  the binary, source, and manual page files for a comand

         $ whereis  whereis
            whereis: /usr/bin/whereis /usr/share/man/man1/whereis.1.gz

2) locate:   locate uses a database created by an updatedb to efficiently locate files. Works great, assuming your database is updated often enough to be reasonable upto date. Most boxes using locate have the updatedb occuring in cron.  On my ubuntu box, I got a long list of files when I tried to locate  command.   RTFM locate

$locate locate

3)  find:      find is perhaps one of the most powerful commands there is.   However, find is slow compared to locate as it  recursively search the paths supplied to  it. 

    The syntax of find is specified like this.      
find path-list expression
It may look rather cryptic. 
Even though the man page lists only three  parts for the command as above, 
for simplicity  we can imagine  that  find  syntax  is havng  four fields.               
1 2 3 4
find starting point find which files action on result
You can formulate your find command based on the above table. For example,
  if you want to find all  avi files in a folder named movies  

1 2 3 4
find  movies -name "*.avi"  -print
      $find  movies   -name "*.avi"  -print
Here are some examples you can try

a) to find all directories on the system whose permissions of 777

     $   find / \( -type d -a -perm -777 \) -print

b) find all core files in home directories and remove them

     $    find /home -name core -exec rm {} \;

c) find all files owned by a particular user no matter whose home directory they are in:

    $  find /home -user -print

d) find all files that have been modified (or had their modification time changed) in the last 30 days:

       $ find / -mtime -30 -print

e) find all tmp files older than 30 days and remove:

      $ find /dirpath \( -name \*.tmp -a -mtime +30 \) -exec rm {} \;

The man page of find has several other option that you can try.

No comments: