Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 95 ยท Working with Text

diff, comm and patch

Learn to compare files with diff, comm and cmp, read unified diff hunks, and create and apply patches with diff -u and patch -p1, using runnable examples.

"What changed?" is one of the most common questions in software. Which lines differ between two config files? What did the new release change in the source tree? Are these two backups identical? Linux has a family of small tools for exactly this. diff shows the differences between files or whole directories, cmp answers "same or different?" byte by byte, comm compares two sorted lists, and patch takes a recorded difference and applies it to a file, so a change can travel as a small text file instead of a whole copy.

The diff format you learn here is not a niche detail. It is what Git shows when you run git diff, what code review tools render, and what mailing lists have used to send changes for decades. Reading a unified diff fluently is a core skill; see also Git status and diff for the same format inside a repository.

cmp and checksums: are these files the same?

If you only need a yes or no, you do not need diff. cmp compares two files byte by byte and prints nothing when they are identical. If they differ it reports the first difference. Its exit status is the real answer: 0 identical, 1 different, 2 trouble (for example a missing file). cmp -s stays silent and is made for if statements.

For comparing files that are far apart (on different machines) you compare checksums instead: sha256sum file prints a fingerprint, and equal files always have equal fingerprints.

Bash cmp, exit status and checksums

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The cut -c1-16,65- keeps only the first 16 characters of each 64-character hash plus the file name, to keep the output short. Real scripts compare the whole hash.

diff: the default (normal) format

diff old new prints the instructions that would turn old into new. In the original "normal" format each change starts with a line like 2c2: line numbers in the first file, a letter, line numbers in the second file. The letters are a (add), d (delete) and c (change). Lines starting with < come from the first file, lines starting with > from the second.

Bash diff in normal format

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Read the first block line by line. 2c2 means "line 2 of the old file was changed into line 2 of the new file"; < shows bananas, > shows blueberries. 4a5 means "after line 4 of the old file, add line 5 of the new file", which is elderberries. The exit status is 1 when files differ, which is not an error: diff uses 0 for same, 1 for different and 2 for real trouble.

Unified diffs: the format everybody uses

The normal format has no context, so you cannot see where in the file a change is. The unified format (diff -u) fixes that and is the standard for patches, Git and code review. It shows a few unchanged lines of context (3 by default) around each change.

A unified diff has a header with two lines and then one or more hunks:

TEXT
--- old.txt          the "from" file (lines removed are marked with -)
+++ new.txt          the "to" file   (lines added are marked with +)
@@ -1,4 +1,5 @@      hunk header: old start,length  new start,length
 apples              a leading space = context, unchanged
-bananas             a leading minus = removed
+blueberries         a leading plus  = added
 cherries
 dates
+elderberries

@@ -1,4 +1,5 @@ means: this hunk covers 4 lines of the old file starting at line 1, and 5 lines of the new file starting at line 1. Normally the header lines also contain file modification times, which differ on every run. To keep the output reproducible we replace them with fixed names using --label, which is also exactly what you do when you want clean a/ and b/ paths for patches.

Bash diff -u and reading hunks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

In the last example the two edits are far apart, so diff prints two hunks, each with three lines of context before and after. If the edits were closer than six lines, the contexts would overlap and merge into one hunk. A hunk header such as @@ -25,6 +25,6 @@ always tells you where the hunk applies in each file.

Plain diff -u old new includes the modification time of each file in the header lines, for example --- old.txt 2026-03-01 10:00:00.000000000 +0000. The patch tool ignores it. We use --label only to make the output the same on every run.

Side by side and other formats

diff -y (or --side-by-side) shows two columns, diff --color highlights changes on a terminal, and diff -c prints the older "context" format. diff -u is the one to learn; everything else is a presentation choice.

Bash diff -y side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Comparing directories with diff -r

With -r (recursive) diff walks two directory trees and compares files with the same relative path. Files that exist in only one tree are reported as Only in .... Add -N to treat a missing file as empty, so that the diff contains the full text of new files (this is what you want when you create a patch for a whole project).

Bash diff -r on two directory trees

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

When you diff directories recursively, the header lines for each file show the full paths and the modification times. In the example above we compare two single files with labels so that the output is stable; the -rq forms print only names and are always deterministic.

Creating and applying a patch

A patch is just the output of diff -u saved in a file. patch reads it and edits files to match. The workflow of every open source project before Git was exactly this: make a copy of the source, edit the copy, run diff -ru original edited > fix.patch, send the file; the receiver runs patch -p1 < fix.patch in their own copy.

The -p1 option tells patch how many leading directory components to strip from the file names in the patch. A patch made with a/config.ini and b/config.ini has one leading component, so -p1 leaves config.ini, which is what you want inside your working directory.

Bash Create a patch and apply it with patch -p1

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

patch prints patching file config.ini and edits the file in place. Because the hunk carries context lines, patch can find the right place even if the file has moved a few lines (it reports an "offset"). If the context no longer matches, it refuses the hunk and writes it to a .rej file.

Dry runs, reverse patches and failures

Always try a patch with --dry-run first: it does everything except write. patch -R applies a patch in reverse, which undoes it. Let us watch what happens when a patch does not fit.

Bash patch --dry-run, -R and a rejected hunk

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

When patch fails it reports Hunk #1 FAILED at 1. and exits with status 1. The unapplied hunk is in list.txt.rej next to the file and you merge it by hand. Remember that a failed patch may still have changed other files in the same patch, so for important work apply it to a copy or use --dry-run first. If you work in a Git repository, git apply does the same job more strictly (it is all-or-nothing), see Git status and diff.

Patching with a backup

patch -b (or --backup) saves the original as file.orig before changing it. That is handy when you want to compare or restore the original quickly.

Bash patch -b keeps a backup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

comm: comparing two sorted lists

diff is line by line in order. When you only care about sets (which items are in list A but not in list B), comm is the right tool. It needs both inputs sorted and prints three columns: lines only in file 1, lines only in file 2, and lines in both. You suppress columns with -1, -2 and -3.

Bash comm: three columns and set operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

comm -23 a b ("lines unique to a") and comm -12 a b ("lines in both") are the two forms you will use most. They can compare lists of users, installed packages or file names. Sort both lists with the same locale: comm <(sort a) <(sort b) handles unsorted input (the <( ) syntax is process substitution).

The three-way idea

Sometimes two people change the same original independently. diff3 and merge take three files: the common ancestor and two modified versions. Where the changes do not overlap they merge them automatically; where they collide they mark a conflict. git merge is built on exactly this idea, and the conflict markers you see in Git (<<<<<<<, =======, >>>>>>>) come from the same tradition. The tool diff3 is available on most systems:

Bash diff3: merge two edits of the same original

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The argument order is mine, base (the common ancestor), theirs. The status is 1 when there were conflicts, and the output contains the conflict markers that you resolve by hand. You will meet this in practice in Merge conflicts.

Choosing the right comparison tool

TEXT
Are they identical?           cmp -s a b      or compare sha256sum values
What lines changed?           diff -u a b
What changed in a project?    diff -ruN old/ new/
Save and share a change       diff -u ... > x.patch ; patch -p1 < x.patch
Which items are in A, not B?  comm -23 <(sort A) <(sort B)
Merge two edits of one base   diff3 -m mine base theirs

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the exit status 1 of diff a b mean?

    diff exits with 0 when the files are identical, 1 when they differ and 2 when there was trouble. Status 1 is therefore a normal result, not an error.
  2. 2. In a unified diff, what does a line starting with a single space mean?

    Lines starting with - were removed, + were added and a leading space marks unchanged context that lets patch locate the hunk.
  3. 3. A patch contains paths like a/src/app.py and b/src/app.py. Which command applies it from the project root?

    -p1 strips one leading path component (the a/ or b/), leaving src/app.py relative to the current directory.
  4. 4. Which command prints the lines that appear only in sorted file x and not in sorted file y?

    comm prints three columns: only in x, only in y, in both. -23 hides columns 2 and 3, leaving the lines unique to x.
  5. 5. How do you undo a patch that was applied from change.patch?

    patch -R applies the patch in reverse, turning the new lines back into the old ones.

Summary

  • cmp -s answers "identical?" with an exit status; checksums such as sha256sum do the same across machines.
  • diff old new exits 0 when files are identical and 1 when they differ. The unified format diff -u is the standard: - removed, + added, a space is context, and @@ -a,b +c,d @@ locates each hunk.
  • diff -r compares directory trees, -q only names differing files and -N treats missing files as empty.
  • Save diff -u output as a patch and apply it with patch -p1; use --dry-run first, -R to undo and -b for backups. Failed hunks end up in .rej files.
  • comm compares two sorted lists: -23 unique to the first, -13 unique to the second, -12 common.
  • diff3 -m merges two edits of a common ancestor and marks conflicts, the idea behind git merge.

Next: Building Text Pipelines