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
- Create a patch from unstaged changes:
git diff > fix.patch
- Create patches from commits:
git format-patch -1 abc1234
- Apply a patch:
git apply fix.patch
- Apply a formatted patch with commit:
git am < 0001-fix.patch
Tips
git format-patchpreserves 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 applydoes not create commits; usegit amfor that.