Posted December 9, 2010 by Spyros in Linux Tips

Head and Tail Linux Commands : The Silent Power


There are some linux commands that are underestimated by nature. Two such commands are head and, even more importantly, tail. In short, head and tail are used to provide output of the first and last lines of a file. For instance, if you execute :


head filename

You will get the first 10 lines of the file with the name “filename”. If you specify the switch -n, you can set how many lines of output you want. For instance :

head -n 5 filename

will print the first 5 lines of the file. The exact same happens with tail, with the difference that tail prints out the last lines of  a file, Therefore :

tail -n 3 filename

will print the last 3 lines of the file with thee name “filename”

The Real Power

The raw power comes from combining commands, most times. Think of a scenario where you want to find the 3 most recently accessed/edited files of a certain directory, let’s say, named ‘downloads’. Sounds like you have to traverse the whole nine yards, but what about :

ls -t | head -n 3

Piping the ls results through head, so that you get the 3 most recently changed files.

More Power With Tail -f

Executing tail with the switch -f is one of the standard administration routines. The reason is that -f instructs tail to never read the End of a File. This means that tail remains open and reads the file in real time. Therefore, at times where you want to dynamically check the logs of, let’s say, apache, you just execute :

tail -f apacheLogFile

then test what you need to test, and have tail print out the output in real time.