How to View the Contents of a File in Linux Using the Cat Command

When working in the Linux terminal, you frequently need to inspect the contents of configuration files, logs, or scripts. While you could open these files using a text editor like nano or vim, doing so is often unnecessary and poses a small risk of accidentally modifying a critical file.

Instead, the most efficient way to quickly read the contents of a file directly in your terminal window is by using the cat command.

What is the Cat Command?

The cat command (short for “concatenate”) is a standard Unix utility that reads data from files and outputs their contents directly to the standard output (your terminal screen). It is fast, safe, and guarantees that you are only reading the file, not editing it.

How to View a Single File

The basic syntax for using the command is incredibly simple: type cat, followed by a space, followed by the path to the file you wish to read.

For example, to view the contents of your system’s hostname configuration file, you would run:

cat /etc/hostname

As soon as you press Enter, the text inside the file will be printed directly to your screen, and your command prompt will immediately return.

Useful Cat Command Flags

While basic viewing is the most common use case, cat includes several helpful flags that format the output to make it easier to read.

1. Displaying Line Numbers

If you are reviewing a script or a piece of code and need to know exactly which line a specific variable is on, you can force cat to number every line of the output by using the -n flag:

cat -n /etc/passwd

2. Showing Hidden Characters

Sometimes scripts fail because of invisible trailing spaces or incorrect line breaks. You can use the -E flag to display a $ symbol at the exact end of every line, making it instantly obvious if there is trailing whitespace:

cat -E myscript.sh

When NOT to use Cat

While cat is excellent for short configuration files, it is not the right tool for viewing massive system logs. If you use cat on a 10,000-line log file, all 10,000 lines will instantly scroll past your screen in a blur, leaving you staring at the very bottom.

If the file you want to view contains more text than can fit on your monitor, use the less command instead (e.g., less /var/log/syslog). The less command allows you to scroll up and down through the file using your arrow keys, making large files easily readable.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.

Receive our best articles and tips delivered straight to your inbox.