diff and patch

Intermediate · 10 min

Compare files and directories with diff, read unified diffs, share a change as a patch file, apply it with patch -p1, undo it with -R, and handle rejects.

Before thisRedirectionPipes and pipelinesCreating, copying, moving and removing

Luke Smith · 10 min

diff and patch

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Luke SmithReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • diff compares two files and prints the lines that differ. Its exit status is 0 for identical, 1 for different and 2 for trouble, so scripts can branch on it.
  • Use diff -u for unified format: a few context lines, - for removed and + for added. It is what Git uses and what patch expects.
  • diff -ruN old new compares directory trees, including files that exist on only one side. Save the output with > change.patch to share a change.
  • patch -p1 < change.patch applies a diff, stripping the first path component. Try --dry-run first, and patch -R reverses a patch.
  • When the target no longer matches, patch applies what it can, saves the rest in a .rej file, and exits 1. A .orig file keeps the earlier copy.

Showing what changed

You edited a config file and something broke. Or a colleague sent you a “fixed” copy of a script. The question is the same: what is different? Reading two files side by side is slow and you will miss lines. diff does it by finding the shortest set of line edits that turns one file into the other.

That set of edits is also useful on its own. If it is small and precise, you can send it to someone and they can replay it on their copy. That is a patch, and patch is the tool that applies it. Git is built on the same idea, so it helps to know the originals. I ran everything here on macOS (Apple diff, based on FreeBSD, and patch 2.0-12u11-Apple). GNU diff and patch on Linux share the options used here, and I did not run them.

I used two versions of a config file, v1/app.conf and v2/app.conf.

The default output

$ diff v1/app.conf v2/app.conf
2,3c2,3
< port=8080
< log=info
---
> port=9090
> log=debug
4a5
> retries=3

< lines are from the first file and > from the second. 2,3c2,3 reads “lines 2 to 3 changed into lines 2 to 3”, and 4a5 is “after line 4, add line 5 from the second file”. This is accurate but hard to apply to a file that has moved a few lines since.

Exit status

diff is also a test, which makes it useful in scripts:

$ diff v1/app.conf v2/app.conf; echo "exit=$?"
...
exit=1
$ diff v1/app.conf v1/app.conf; echo "exit=$?"
exit=0
$ diff v1/app.conf nope; echo "exit=$?"
diff: nope: No such file or directory
exit=2

The surprise is that 1 is not failure. It means “found differences”. In set -e scripts and || chains, check for 2 explicitly. See the exit status lesson.

Unified format

Use -u. It shows a few unchanged lines of context around each change, and patch can use that context to find the right place:

$ diff -u v1/app.conf v2/app.conf
--- v1/app.conf	2026-11-23 02:54:10
+++ v2/app.conf	2026-11-23 02:54:10
@@ -1,4 +1,5 @@
 host=localhost
-port=8080
-log=info
+port=9090
+log=debug
 timeout=30
+retries=3

- removed, + added, a space for context. @@ -1,4 +1,5 @@ says “the old text starts at line 1 for 4 lines, the new at line 1 for 5”. This is the format git diff prints, as in the Git lesson on reading history. -U 0 removes the context lines, which makes a diff compact but fragile. Side-by-side output exists too, with diff -y -W 50, which marks changed lines with | and added ones with >.

Whole directories

-r recurses, and -q just names the files that differ:

$ diff -rq v1 v2
Files v1/app.conf and v2/app.conf differ
Only in v2: new.txt

For a patch you can ship, use -ruN: recursive, unified, and treating a file missing on one side as empty (-N), so new files come through. Save it with redirection:

$ diff -ruN v1 v2 > tree.patch

Applying a patch

I copied v1 to w2 and applied the tree patch from inside it:

$ cd w2; patch -p1 < ../tree.patch
patching file app.conf
patching file new.txt
$ ls
app.conf  new.txt

-p1 is “strip one leading path component”. The patch names v1/app.conf and v2/app.conf, and from inside w2 there is no v1/, so you strip it. -p0 would keep paths as written, and -p2 strips two. Getting -p wrong is the most common reason for “can’t find file to patch”. Git patches use a/ and b/ prefixes, so -p1 is the usual value there too.

Check before changing anything with --dry-run:

$ patch --dry-run -p1 < ../change.patch
patching file app.conf

It reports what it would do and touches nothing. For a single-file patch, name the file: patch work/app.conf < change.patch worked on my copy. And a patch reverses with -R:

$ patch -R work/app.conf < change.patch
patching file 'work/app.conf'
$ diff work/app.conf v1/app.conf && echo "back to v1"
back to v1

When the file has changed

A patch assumes the target looks like the original. I changed host in the work copy to prod and port stays the same, then applied the patch again:

$ patch work/app.conf < change.patch
patching file 'work/app.conf'
1 out of 1 hunks failed--saving rejects to 'work/app.conf.rej'
$ ls work
app.conf  app.conf.orig  app.conf.rej

The hunk includes host=localhost as context, and the file now says host=prod, so the context did not match. patch refused the hunk, kept the unmodified file as .orig, and wrote the failed hunk to .rej. Exit status was 1. You apply the change by hand and delete the leftovers. When a whole change fails like this on a shared project, a Git merge conflict is the same situation with better tools.

Small things worth knowing

  • diff -b ignores whitespace changes. Two files differing by a double space differed by plain diff -q and matched with -b.
  • Process substitution, from the subshells lesson, compares command output without temp files: diff <(sort a) <(sort b).
  • git diff --no-index v1 v2 compares any two paths with Git’s output, even outside a repository. It printed a stat summary and exit status 1 in my test.

About the video

“Wrap Your Brain around ‘Patch’ and ‘Diff’ on Linux” is a 10-minute 20-second video from Luke Smith, published May 2019. The description is just links, with no chapters, and I could not read a transcript, so I am going by the title. It is an English-language channel. It is older than the other picks, but diff and patch have not changed. The creator has strong opinions on tools in other videos, which are not part of this one as far as the title says.

Where this fits

diff and patch move changes between files on one machine. The next lesson moves bytes over a network: fetching with curl and wget.

Check yourself

  1. 01What does the exit status of diff tell you?

    0 means no differences, 1 means differences were found, and 2 means an error such as a missing file. That is why diff in an if statement treats a difference as false.

  2. 02You have a tree patch that names v1/app.conf and v2/app.conf. How do you apply it inside a copy of v1?

    cd into the copy and run patch -p1 < tree.patch. The -p1 strips the first path component (v1/ or v2/) so the paths match.

  3. 03How do you undo a patch you applied?

    Run patch -R with the same patch file on the patched file. The reversed patch restores the earlier text.

  4. 04patch printed '1 out of 1 hunks failed'. What exists now and what do you do?

    A .rej file holding the failed hunk, and usually a .orig backup. Open the .rej, make the change by hand, then delete the extra files.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark