Log watching using tail or less

Using tail

The tail utility is similar to head but by default displays the last ten lines of a file. Depending on how you invoke it, this utility can display fewer or more than ten lines. You can monitor lines as they are added to the end of the growing file named logfile by using the following command:

$ tail -f logfile

Log files typically grow in size, with the latest contents appended to the end of the log. I often need to watch a log file in live action, for error detection. The command “tail -f” will display the last 10 lines of a file, and then continuously wait for new lines, and display them as they appear.

$ tail -f /var/log/messages

Press the interrupt key (usually CONTROL-C) to stop tail and display the shell prompt. If you want to see more than ten lines at the outset, specify the new number (say 50 lines) like this:

$ tail -50  -f /var/log/messages

Using less

When you want to view a file that is longer than one screen, you can use either the less utility or the more utility. Each of these utilities pauses after displaying a screen of text; press the SPACE bar to display the next screen of text. Because these utilities show one page at a time, they are called pagers. Although less and more are very similar, they have subtle differences. At the end of the file, for example, less displays an END message and waits for you to press q before returning you to the shell. In contrast, more returns you directly to the shell.

The tail command is fast and simple. But if you want more than just following a file (e.g., scrolling and searching), then less may be the command for you.

$ less /var/log/messages

Press Shift-F. This will take you to the end of the file, and continuously display new contents. In other words, it behaves just like tail -f.

Starting less in tail mode

To start less in the tail mode, execute:

$ less +F /var/log/messages

To scroll backward, you must first exit the follow mode by pressing Control-c. Then, you can scroll back by pressing b. In fact, all the less commands are available to you once you are in the regular less mode. You can start a search by typing/followed by the string you want to search for.

Related Post