How can I stage only selected lines of a file in Git?
Quick answer
Run git add -p path/to/file to review changes in that file and choose which to stage. If a displayed hunk mixes changes you want and changes you do not, try splitting it or editing it when those options are available. Then run git diff --cached and check that the staged diff contains only the changes intended for the next commit. [S1] [S2]
The question, the details, the next step.
A practical checklist
Name the file and the specific change intended for the next commit.
Run
git add -p path/to/fileand read each displayed hunk before selecting.Try splitting a mixed hunk; use the edit option only if you can review its result confidently.
Run
git diff --cachedafter selection.Confirm the staged diff includes the intended change and excludes unrelated lines.
A few more useful answers
Does `git diff --cached` show every change in my working tree?
No. It shows changes staged for the next commit relative to HEAD by default; it is a check of the index, not a general review of all unstaged working-tree changes. [S2]
Can interactive patch mode split a displayed hunk?
Yes. Git’s interactive patch mode offers options to split a hunk or edit it. [S1] Review the staged diff afterward to verify the result.
What if `HEAD` does not exist yet?
The Git documentation says git diff --cached shows all staged changes when HEAD does not exist. [S2]
Sources
References used for this guide.
- [S1] Git add: interactive patch staging git-scm.com · Checked
- [S2] Git diff: reviewing staged changes git-scm.com · Checked
