Skip to content
Latchkey

patch: Apply a Unified Diff to Files

patch reads a diff and applies the described changes to the target files, the classic way to apply a .patch in a build.

patch is what you reach for when a diff was produced outside Git. The two things to get right are the strip level (-p) and whether the patch still applies cleanly.

What it does

patch takes a unified or context diff and edits the referenced files to match the "new" side. The -p<n> flag strips n leading path components from the filenames in the diff so they resolve against your working directory. Exit status is nonzero if any hunk fails.

Common usage

Terminal
patch -p1 < changes.patch
# preview without touching files
patch -p1 --dry-run < changes.patch
# undo a previously applied patch
patch -p1 -R < changes.patch

Options

FlagWhat it does
-p<n>Strip n leading path components from filenames
--dry-runShow whether it would apply, changing nothing
-RReverse: undo the patch
-i <file>Read the patch from a file instead of stdin
-bBack up each file before patching (.orig)
--fuzz=<n>Allow n lines of context mismatch

In CI

Run patch -p1 --dry-run < file.patch first so a bad patch fails fast without leaving files half-edited. The -p1 level matches patches generated by git diff or diff between a/ and b/ trees; a patch made with plain diff of two bare filenames often needs -p0.

Common errors in CI

"patch: **** malformed patch at line N" means the diff is corrupted, usually by CRLF conversion, editor wrapping, or a copy-paste that lost the leading space on context lines. "Hunk #1 FAILED at 42" with a .rej file means the target file no longer matches the patch context (the code moved on); rebase or regenerate the patch. "can't find file to patch" means the wrong -p level. Reversed or already-applied patches prompt "Reversed (or previously applied) patch detected!".

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →