How to Compare Files Using cmp

How to Compare Files Using cmp

Hey there! 👋 Welcome to this beginner-friendly Linux tutorial from ProgramGuru.org. Today, we're going to learn how to compare two files using a simple but powerful command called cmp.

If you're wondering whether two files are identical, or if there's even a small difference between them, cmp is the tool you need. Let's break this down slowly and clearly so that anyone—even if you're new to Linux—can follow along!

🔧 What is cmp?

cmp stands for "compare." It compares two files byte by byte and tells you the first point where they differ. If the files are identical, it says nothing. That’s right—it stays quiet. Silence means success!

📌 Basic Syntax

cmp file1 file2

Let’s try it out with some examples!

📁 Step 1: Create Two Files

First, let’s create two simple text files for comparison:

echo "Hello world!" > fileA.txt
echo "Hello world!" > fileB.txt

Now let’s compare them:

cmp fileA.txt fileB.txt

Output:


(no output — which means they are exactly the same!)

✏️ Step 2: Change One File

Now, let’s make a small change to fileB.txt:

echo "Hello world!!!" > fileB.txt

Try the compare command again:

cmp fileA.txt fileB.txt

Output:


fileA.txt fileB.txt differ: byte 13, line 1

This tells us that the difference starts at byte 13, on line 1. Simple and precise!

🔍 Use -l to Show Byte Differences

If you want to see what exactly is different in terms of byte values, use the -l option:

cmp -l fileA.txt fileB.txt

Output:


13 41 41
14 0 41
15 0 41

This tells you the byte position and the differing byte values in octal.

📄 Use -s for Silent Mode

If you just want to know whether the files differ, and don’t care where, use the silent flag:

cmp -s fileA.txt fileB.txt

This will give no output if the files are the same, and exit silently. But you can check the result using:

echo $?

Output:


0   (means files are the same)
1   (means files are different)

✅ Summary

  • cmp file1 file2 — Basic comparison
  • cmp -l — Show byte-by-byte differences
  • cmp -s — Silent mode for scripting

That’s it! 🎉 You now know how to compare files in Linux using cmp. This is especially useful when working with scripts, config files, or debugging subtle file differences. Keep experimenting and you’ll get the hang of it!

See you in the next tutorial on ProgramGuru.org!