Linux: How to view log files on the shell

Many Linux servers are administered on the command line e.g. with an SSH connection. In the following article, I will explain several shell commands that make it easy to view log files. These commands will work on all major Linux distributions inc. CentOS, Debian, Fedora, and Ubuntu.

Get the last N lines of a log file

The most important command is "tail". The tail command can be used to read the last lines from a file. Examples:

Get the last 100 lines from the Debian mail log file:

tail -n 100 /var/log/mail.log

Result:

View log using tail command

 

Get new lines from a file continuously

To get all newly added lines from a log file in realtime on the shell, use the command:

tail -f /var/log/mail.log

to quit tail and go back to the command line press the keys [ctrl] + [c]

Get the result line by line

If you want to get the last 1000 lines from a log file and they do not fit into your shell window, you can use the command "more" to be able to view them line by line.

tail -n 1000 /var/log/mail.log | more

press [space] on the keyboard to go to the next line or [ctrl] + [c] to quit.

Search in a log file

If you want to search for a specific term in a large file, the command "grep" comes in handy.

Example: We search for the email address "[email protected]" in the mail log file:

grep "[email protected]" /var/log/mail.log

To store the result of the above grep command into a file named result.txt, use this command:

grep "[email protected]" /var/log/mail.log > /tmp/result.txt

View the whole content of a file

If you want to view the whole content of a file on the shell, use the command "cat". Example:

cat /proc/cpuinfo

will show you detailed info about the CPU of your computer.

Leave a Comment

*