Using Git Add Patch for Precise Staging
You'll learn how to stage specific parts of a file instead of the entire file, giving you surgical control over what goes into each commit.
Why Stage Parts of a File?
Sometimes you've made multiple logical changes in a single file—maybe you fixed a bug and added a new feature. To honor the principle of atomic commits (one logical change per commit), you need to split these changes into separate commits. That's where git add -p (patch mode) comes in.
How Git Add Patch Works
Instead of staging an entire file with git add filename, use:
git add -p filename
Git will break your changes into hunks—discrete chunks of modifications—and ask you about each one:
Stage this hunk [y,n,q,a,d,s,e,?]?
Your main options:
- y – yes, stage this hunk
- n – no, skip it for now
- s – split into smaller hunks (if possible)
- q – quit; don't stage this or remaining hunks
- ? – show all options
Real-World Example
Imagine you fixed a typo in a function and also added logging. Using -p, you can stage just the typo fix for one commit, then stage the logging changes for a separate commit—even though both changes are in the same file.
This keeps your commit history clean, making code reviews easier and future debugging (via git blame or git bisect) more effective.
Key Takeaway: git add -p lets you selectively stage hunks of changes within files, enabling precise, atomic commits that separate different logical changes—even when they share the same file.