VIEW FILES USING THE HEAD AND TAIL COMMANDS

When viewing text files on Linux, most people typically use the cat command or less/more pagers. These tools allow you to view the full file either at once or a screen at a time.

Other tools allow you to view select parts of a file. As their names suggest, the head command allows you to view the beginning of a file, and the tail command allows you to view the end of a file.

A number of options determine how much of the file you can view. For example, to view the first 20 lines of a file, execute the following:

$ head -20 file.txt

By default, both the head and tail commands display 10 lines of text at a time. By passing head (or tail) an argument, such as in the example above, you can view the first 20 (or last 20) lines of a file.

To begin viewing lines at a specific point in a file, you can use the + switch with the tail command. For example, to begin viewing a file from line 50 to the end of the file, use the following:

$ tail +50 file.txt

In addition, you can use the tail command to view text in a file even if there's been an addition of new data to the end of the file. This is particularly useful for monitoring log files, allowing you to see new entries to the log file as the system adds them. For example, execute the following:

# tail -f /var/log/messages

You most likely need to be root to accomplish this, but the command above "follows" the /var/log/messages file. Tail will display lines on the screen as the system adds them to the file. And if you ever rotate a log file, the tail command is smart enough to begin following the new file, provided it has the same name.