The standard cat command is one of the first utilities Linux users learn. It reads a file and prints its contents to the terminal screen starting from line one and finishing at the bottom. However, when dealing with chronological server logs or system error outputs, the most critical information—the most recent event—is always at the very bottom of the file. Reading these files top-to-bottom is inefficient. To solve this, Linux includes the tac command, which is literally the word “cat” spelled backwards.
What Does the tac Command Do?
The tac command reads a text file and outputs it to the standard output (your terminal screen) in reverse order. It prints the absolute last line of the file first, followed by the second-to-last line, continuing until it prints line one at the very bottom of your screen. Crucially, it reverses the order of the lines, not the characters. The text itself remains perfectly readable.
Basic Reverse Printing
Using the command is as simple as using its forward-reading counterpart. Assume you have a file named apache_errors.log.
- Open your terminal application.
- To view the file with the most recent entries at the top, type:
tac apache_errors.log
Press Enter. The file will print to the screen in reverse. It is important to note that tac does not modify the original file; it only alters how the data is presented on your screen.
Combining tac with Text Pagers
If your log file contains 10,000 lines, running tac by itself will simply flood your terminal screen, and the most recent entries (which printed first) will instantly scroll out of view. To make the output readable, you must pipe the reversed output into a pager utility like less.
tac apache_errors.log | less
This command reverses the file and immediately pauses the output, presenting you with the very last line of the file at the top of your screen. You can then use the arrow keys to scroll down through the file chronologically backward.
Extracting a Specific Number of Lines
While the tail command is excellent for viewing the bottom of a file, it still prints those lines in standard top-to-bottom order. If you want to extract the last 20 lines of a file but you want them presented in reverse order (newest first), you can combine tac with the head command.
tac apache_errors.log | head -n 20
Because tac flips the file upside down, the head command (which grabs the top of a stream) now effectively grabs the bottom 20 lines of the original file, presenting them in perfect reverse-chronological order. This combination is an essential tool for rapid server diagnostics.