How to create and apply patches in Git

· Category: Git

Short answer

Use git diff or git format-patch to create patches, and git apply or git am to apply them.

Steps

  1. Create a patch from unstaged changes:
git diff > fix.patch
  1. Create patches from commits:
git format-patch -1 abc1234
  1. Apply a patch:
git apply fix.patch
  1. Apply a formatted patch with commit:
git am < 0001-fix.patch

Tips

  • git format-patch preserves author and commit message metadata.
  • Check if a patch can apply cleanly with git apply --check.
  • Patches are useful for code review over email or offline sharing.

Common issues

  • Whitespace conflicts: use git apply --whitespace=fix.
  • git apply does not create commits; use git am for that.