Create and Apply Patches with diff -u and patch

Generate a unified diff between two files, apply it to another copy with patch, and reverse it with patch -R.

LinuxdiffpatchtextLow risk
Run `diff -u old new > fix.patch` to create a patch, then `patch file < fix.patch` to apply it (and `patch -R` to reverse).

01Command

Command
$ diff -u original.txt new.txt > changes.patch && patch original.txt < changes.patch

02What it does

Without -u you get terse normal diffs; the unified format includes context lines so patch can locate changes even if line numbers shifted. Preview safely with `patch --dry-run < fix.patch` before applying, and note that for directory trees, `diff -ruN olddir newdir` plus `patch -p1` is the standard convention. No exit code tricks needed: diff exits 1 when files differ, 0 when identical — useful in shell scripts.

03Risk

RiskLow risk
Requirementsdiffutils and patch (patch may need installing: apt install patch)

04Undo

Undo
$ patch -R original.txt < changes.patch

05Sources

  • patch(1) - Linux manual page
    Ubuntu Manpages · technical · 2026-09-17
    Evidence: patch applies a diff to a file, with -R to reverse the patch and --dry-run to preview the result without modifying files.
  • diff(1) - Linux manual page
    Ubuntu Manpages · technical · 2026-09-17
    Evidence: diff -u outputs the differences in unified context format suitable for consumption by the patch program.

Last verified: 2026-09-17 · Category: Files & Folders