Skip to content
Applying a Patch
step 1/5

Reading — step 1 of 5

Read

~1 min readProduction

Applying a Patch

The patch command applies a unified diff to a file:

$ patch < changes.patch
patching file foo.txt

Algorithm:

  1. Read the patch header to find file paths.
  2. For each hunk: a. Find the context lines in the target file (fuzzy match: hunks may not be at exact line numbers if the file changed since the patch was created). b. Apply the deletions and additions.
  3. Save the result.

Fuzzy matching: patch is forgiving. If line numbers shifted by a few, it tries offsets. The "Hunk #X succeeded at line Y (offset Z lines)" message means it found the change but at a different position.

If the patch DOESN'T match (context doesn't line up), the hunk is rejected and saved to a .rej file. You manually integrate.

git apply --3way is even smarter: tries a 3-way merge using the original commit's content as base.

Tools that GENERATE patches from diffs:

  • git format-patch — patch series for email
  • diff -u — unified format
  • pprof and other profilers — showing changes between runs

Tools that APPLY patches:

  • patch -p1 (strip 1 path component)
  • git apply
  • quilt (patch stack management)

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…