Git Patch
Learn how to create and apply patches with Git
Git Patch
Git patches allow you to share changes as files without using a remote repository. Useful for code reviews, contributions, and offline sharing.
Creating Patches
From Commits
# Create patch from last commit
git format-patch -1 HEAD
# Create patch from last 3 commits
git format-patch -3 HEAD
# Create patch from specific commit
git format-patch commit-hash -1
From Differences
# Create patch from unstaged changes
git diff > changes.patch
# Create patch from staged changes
git diff --staged > staged.patch
# Create patch between branches
git diff main..feature-branch > feature.patch
Applying Patches
Apply with git apply
# Apply patch file
git apply changes.patch
# Check if patch can be applied
git apply --check changes.patch
# Apply with statistics
git apply --stat changes.patch
Apply with git am
# Apply patch with commit message
git am 0001-feature-patch.patch
# Apply multiple patches
git am *.patch
Common Use Cases
Contributing to Projects
# Create patch for contribution
git format-patch -1 HEAD --stdout > my-contribution.patch
# Send patch file to maintainer
Code Reviews
# Create patch for review
git format-patch main..feature-branch
# Reviewer applies patches to test
git am *.patch
Offline Sharing
# Create patches for offline sharing
git format-patch -o patches/ HEAD~5..HEAD
# Share patches via email/file transfer
Patch Options
Format Patch Options
# Include cover letter
git format-patch --cover-letter -3 HEAD
# Custom output directory
git format-patch -o patches/ -1 HEAD
# Add signature
git format-patch --signature="Your Name" -1 HEAD
Apply Options
# Apply but don't commit
git apply --index patch.patch
# Reverse apply (undo)
git apply --reverse patch.patch
# Apply with 3-way merge
git am --3way patch.patch
Best Practices
- Include descriptive commit messages
- Test patches before sharing
- Use format-patch for complete commits
- Use diff for simple changes
- Include documentation with patches