To commit only part of a file’s changes in Git, use interactive staging (git add -p
or git add --patch
). This allows you to review and select specific changes (hunks) to include in your commit. Here’s how:
Step-by-Step Guide
- Start interactive staging:
git add -p <file> # Replace `<file>` with the path to your file
- This opens an interactive prompt showing chunks of changes in the file.
- Review and select changes:
Git will display a “hunk” (a block of changes) and prompt you with:
Stage this hunk [y,n,q,a,d,s,e,?]?
- Common options:
y
(yes): Stage the hunk.n
(no): Skip the hunk.s
(split): Split the hunk into smaller parts (if possible).e
(edit): Manually edit the hunk (advanced).q
(quit): Exit the interactive session.?
: Show help for all options.
- Split large hunks (if needed):
- If a hunk contains changes you want to split, press
s
to divide it into smaller hunks for finer control.
- Repeat until done:
Continue selectingy
orn
for each hunk until all desired changes are staged. - Commit the staged changes:
git commit -m "Commit message for selected changes"
- Commit remaining changes (optional):
- Repeat the process for other parts of the file or commit the rest later.
Example Workflow
# 1. Start interactive staging for a file
git add -p src/app.js
# 2. Git shows a hunk:
- console.log('Debug message');
+ const result = calculate();
Stage this hunk [y,n,q,a,d,e,?]? y # Stage this change
# 3. Commit the staged changes
git commit -m "Add calculation logic"
# 4. Remaining changes (if any) stay uncommitted
Alternative: Stage Specific Lines with git add -e
For precise line-by-line control:
- Open the file in your editor and manually delete the lines you don’t want to stage.
- Save the file and stage it:
git add <file>
- Undo the edits (restore the original file):
git checkout -- <file>
- Commit the staged lines.
Key Notes
- Unstaged changes remain: Only the selected hunks are staged; the rest stay in your working directory.
- Verify staged changes: Use
git diff --staged
to check what’s been staged before committing. - Undo mistakes: Use
git restore --staged <file>
to unstage all changes in a file and start over.
Best Practices
- Test your code after partial commits to ensure the unstaged changes don’t break functionality.
- Use
git checkout -p <file>
to discard specific changes instead of staging them.