Reading the System: cat, less, head, and tail
·TechSoftware Development

Reading the System: cat, less, head, and tail

Master the tools for inspecting files without leaving the terminal. Learn why 'less' is more than 'more', how to peek at the start or end of massive logs, and the indispensable power of real-time monitoring with 'tail -f'.

Viewing Files: Inspecting Your Data Without a GUI

In the Linux world, especially on servers, you don't "open" a log file in a text editor to read it. That's slow and potentially dangerous (you might accidentally change a line). Instead, we use a set of high-performance utilities designed for reading and monitoring files.

Whether you are checking a configuration file, debugging a 10GB log file, or watching real-time traffic hit your web server, these four commands—cat, less, head, and tail—are your fundamental tools.


1. cat: The Quick Look (Concatenate)

cat is the simplest file viewer. It simply "dumps" the entire contents of a file onto your screen.

cat /etc/hostname

When to use cat:

  • Only for small files (under 50 lines).
  • When you want to combine two files into a third: cat file1.txt file2.txt > combined.txt.

When NOT to use cat:

  • Never use cat on a large file. It will scroll your terminal for miles, and you will lose your place.

2. less: The Professional Pager

In Linux, we have a saying: "Less is More." more was an early tool that let you scroll down through a file. less is a newer tool that lets you scroll up, down, and search.

less /var/log/syslog

Navigating in 'less':

  • Spacebar: Page down.
  • b: Page up.
  • /search_term: Search for something. (Press n for next match).
  • q: Quit.

3. head and tail: Peeking at the Edges

Sometimes you don't want to read the whole file; you just want to see the beginning or the end.

head: The Beginning

By default, it shows the first 10 lines.

head -n 5 access.log # See just the first 5 lines

tail: The End

By default, it shows the last 10 lines.

tail -n 20 access.log # See the last 20 lines

4. The "DevOps Hero": tail -f

This is arguably the most useful command for developers. The -f flag stands for "Follow." It tells tail to keep the file open and display new lines as they are written to the disk in real-time.

# Watch your web server logs as users hit your site
tail -f /var/log/nginx/access.log

5. Practical: Connecting the Dots with Pipes

As we discussed in Module 1, Linux commands are like Lego bricks. You can "pipe" the output of one into another.

# Get the first 50 lines, but scroll through them with less
head -n 50 massive_log.txt | less

# Show the last 10 lines, but only those containing the word "Error"
tail -n 100 access.log | grep "Error"

6. Example: A Real-Time Error Watcher (Python)

Imagine you want a tool that monitors a log file and sends an alert if a specific keyword appears. This Python script mimics the behavior of tail -f and adds logic to look for "Critical" errors.

import time
import os

def follow_log_and_alert(file_path):
    """
    Mimics tail -f and alerts on specific keywords.
    """
    print(f"Watching {file_path} for errors...")
    
    # Go to the end of the file
    file_size = os.path.getsize(file_path)
    
    with open(file_path, 'r') as f:
        # Move pointer to the end of the file initially
        f.seek(file_size)
        
        while True:
            line = f.readline()
            if not line:
                # No new line, wait a second and retry
                time.sleep(1)
                continue
                
            # Logic: If line contains 'ERROR' or 'CRITICAL'
            if "ERROR" in line.upper() or "CRITICAL" in line.upper():
                print(f"\n[!!! ALERT !!!] {line.strip()}")
            else:
                # Just show the heartbeat
                print(".", end="", flush=True)

if __name__ == "__main__":
    # Create a dummy log to watch
    log_file = "test_app.log"
    if not os.path.exists(log_file):
        with open(log_file, "w") as f: f.write("Log Started\n")
        
    print(f"To test this, open another terminal and run:")
    print(f"echo 'DATABASE ERROR' >> {log_file}")
    
    try:
        follow_log_and_alert(log_file)
    except KeyboardInterrupt:
        print("\nWatcher stopped.")

7. Professional Tip: Use 'cat -n' to Debug Code

If you are looking at a configuration file and someone says "Look at line 45," you can use the -n flag with cat to add line numbers.

cat -n /etc/ssh/sshd_config | head -n 50

8. Summary

Reading is as important as writing.

  • Use cat for small files and concatenation.
  • Use less for comfortable, interactive reading and searching.
  • Use head and tail to inspect the boundaries of large files.
  • Use tail -f to monitor active logs and processes.

In the next lesson, we will look at how to work smarter, not harder, by mastering Command History and Tab Completion.

Quiz Questions

  1. How do you search for the word "Failed" inside a file using less?
  2. What happens if you try to cat a 5GB file?
  3. Which command flag allows you to see lines being added to a file in real-time?

Continue to Lesson 5: Command History and Tab Completion—Typing Faster with the Shell.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn