Friday, November 14, 2008

nc - network cat

nc is one of the most useful and unappreciated command. On many systems there is no man page available for it. nc allows you redirect stdin, stdout or stderr to a socket. Many programmers write programs to achieve the same, while a single command can do that work for them.

locate - Unix desktop search

If you are searching for a desktop search system on unix systems with command line interface, locate is the command. locate indexes all the data on your system so that it can answer your queries quickly. Roughly its equivalent to doing a grep on all the files in your system. Problem with grep is that, it might take hours together to findout files containing a specific pattern. locate does it in less than a second.

$ locate pattern ## find files on the system containing this pattern

locate keeps an indexed DB of all the files on your system. It needs to be updated as new files gets added or files gets removed or updated. To update this DB, you can use following commands. On linux you can use -

$ sudo updatedb

On freebsd you can use -

$ sudo /usr/libexec/locate.updatedb

More useful thing to do would be to add this command to your crontab so it updates DB at regular frequency automatically.

$ crontab -e

0 0 * * sun # update locate db, every sunday midnight


locate is very helpful to find files quickly when you rember only some approximate content of it. find and grep can give the same results. But its very time consuming.

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.