When reviewing text files in the Linux terminal, the standard cat command prints the contents starting from line 1 and ending at the bottom of the file. However, if you are reading system log files, error reports, or transaction histories, the most recent and important information is almost always located at the very bottom of the document. Scrolling past thousands of lines just to find the newest entry is inefficient. Instead, you can use the tac command to read the file entirely in reverse.
What is the tac Command?
The tac command is literally cat spelled backwards. It is a standard utility included in the GNU Core Utilities package, meaning it comes pre-installed on virtually every Linux distribution, including Ubuntu. Its sole purpose is to concatenate and print files in reverse order, line by line. The last line of the file becomes the first line printed on your screen.
How to Use tac on a Single File
Using the command is as simple as replacing cat with tac.
For example, if you want to view the system authentication log to see the most recent login attempts first, you would open your terminal and type:
sudo tac /var/log/auth.log
Press Enter. The terminal will output the entire file, but the newest entries at the bottom of the original file will be displayed at the very top of your screen.
Combining tac with Other Commands (Piping)
Because tac reverses the entire file, running it on a massive, 10,000-line log file will still flood your terminal screen, just in the opposite direction. To make it truly useful, you should combine it with commands like head or less using a pipe (|).
Viewing Only the Newest 20 Lines
If you only want to see the 20 most recent entries in a log file, but you want them presented with the newest item first, you can pipe the reversed output into the head command:
sudo tac /var/log/syslog | head -n 20
This flips the entire file upside down, but then immediately cuts it off after showing you only the first 20 lines of the reversed data.
Searching for the Most Recent Error
You can also pipe the reversed file into grep to find the most recent occurrence of a specific error, without having to search through the entire history:
sudo tac /var/log/nginx/error.log | grep -m 1 "Failed to load"
The -m 1 flag tells grep to stop searching after finding the first match. Because tac flipped the file, the “first” match it finds is actually the most recent error that occurred.