The Linux ‘head’ and ‘tail’ commands

Linux head/tail FAQ: Can you share some examples of the Linux head and tail commands?

Sure. The Linux head and tail commands are very similar, so I've included them here together. The head command command prints lines from the beginning of a file (the head), and the tail command prints lines from the end of files. There's one very cool extra thing you can do with the tail command, and I'll show that in the tail example commands below.

The Linux `head` command

By default the head command prints the first ten lines of a file, as shown in this head command example:

head file1

If you want to print more or less than 10 lines from the beginning of the file, the head command -n option lets you specify how many lines you want to see. Here I specify that I only want five lines:

head -n 5 file1

and here I say that I want to see 25 lines:

head -n 25 file1

It's also common to use the Linux head command in a command pipeline, something like this:

ps auxwww | grep apache | head -20

The Linux `tail` command

By default the Linux tail command also prints ten lines of a file, but it prints the last 10 lines, as shown in this tail command example:

tail file1

Like the head command, the tail command also lets you specify a number other than 10 using the -n option:

tail -25 file1

The Linux tail command has another very powerful option: the -f option prints from the end of the file, but also keeps the file open, and keeps printing from the tail of the file as the file itself grows. This is great for looking at the end of a log file. For instance, you can see new lines that are added to the end of an Apache log file, as they are added, like this:

tail -f apache.log

That's an extremely powerful feature that I use often for watching files as they grow (mostly log files of one sort or the other).

Linux head and tail commands - Related links

For more information on the Linux head and tail commands, I've put versions of the head and tail man pages out here on the website:

If you use the search form you can also find other Linux head and tail command examples on this website.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.