Skip to content
Linux Basics: Comparing Files with diff and cmp

Linux Basics: Comparing Files with diff and cmp

October 6, 2026

Before replacing a text file, it helps to see what changed. On Debian and Ubuntu, diff compares files line by line, while cmp compares their bytes.

Prepare two versions

Run mktemp -d, then use cd to enter the temporary directory it prints. Create two small files there:

printf 'apples\nbananas\n' > before.txt
printf 'apples\npears\n' > after.txt

The first line is the same in both files. The second line is different.

Show the changed lines

diff -u before.txt after.txt

-u selects unified format, which includes nearby unchanged lines for context. The file headers identify the two paths. Within a change block, lines beginning with - belong to the first file, and lines beginning with + belong to the second.

This comparison only displays differences. It does not edit either file or apply the changes.

Check whether files match

cmp before.txt after.txt
cmp before.txt before.txt

Example output; diagnostic wording can vary by version and locale:

before.txt after.txt differ: char 8, line 2

cmp reports the first differing byte and line when files differ. When they are identical, it prints nothing. Unlike a line-oriented text comparison, a byte comparison can also check binary files.

Both tools return status 0 for identical files and 1 for differences. A higher status indicates trouble, such as an unreadable file. A difference is an expected result, not necessarily a failed comparison.

You can inspect the most recent command’s status with echo $?. Run it immediately after that command, before running anything else. Start with diff -u when you want to understand a text change and cmp when exact equality matters.

Reference

Debian diff manual

Acknowledgements

This post was created with assistance from AI.

Linux Basics — lesson 10 of 25. Series index

Previous: Selecting Text Fields with cut · Next: Using Environment Variables

Last updated on