Git Add -p: Stage Only Part of a File
Why stage part of a file?
Sometimes one file contains two unrelated edits. git add -p -- path offers groups of nearby changes called hunks. You can choose which groups enter the index. Use a separate new disposable lab outside any repository, so the unfinished Bread edit from lesson 4 stays untouched. The example uses a text file with enough unchanged lines to separate two hunks.
mkdir bytemind-patch-lab && cd bytemind-patch-labgit init -b maingit config --local user.name 'ByteMind Learner'git config --local user.email learner@example.invalidprintf '%s\n' 'Title: Notes' '01' '02' '03' '04' '05' '06' '07' '08' '09' '10' '11' '12' 'Footer: Draft' > guide.txtgit add -- guide.txtgit commit -m 'Add guide baseline'The initial commit contains a title and footer separated by twelve numbered lines. Stop if setup fails.
Select one hunk
Replace the title and footer using the following controlled fixture. The explicit diff.context=3 setting selects three context lines for predictable hunk separation on the tested version. In the interactive prompt type y for the title and n for the footer. y stages the current hunk, n leaves it unstaged, q stops and leaves later hunks unstaged, and ? displays help. Other options depend on the prompt. Always read the actual hunk before answering.
printf '%s\n' 'Title: Git Notes' '01' '02' '03' '04' '05' '06' '07' '08' '09' '10' '11' '12' 'Footer: Final' > guide.txtgit -c diff.context=3 -c diff.interHunkContext=0 add -p -- guide.txtWith the explicit configuration, the tested Git offers two hunks. Answer y then n. The working file remains unchanged by staging.
Review before committing
Check that the staged diff contains only the title edit and the unstaged diff contains the footer edit. If you selected the wrong part, do not commit; the safe unstage commands are covered in the undo chapter. For this disposable practice you can start a fresh lab instead.
git diff --cached -- guide.txtgit diff -- guide.txtgit commit -m "Clarify guide title"git show HEAD:guide.txtgit status --shortThe commit contains Title: Git Notes and Footer: Draft. The working file still contains Footer: Final; status is M guide.txt. Practice in a fresh copy: select only the footer instead, and verify that the recorded title stays unchanged.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Git Add -p: Stage Only Part of a File — knowledge check
Apply the lesson to common beginner repository states.
What is a hunk in patch staging?
What does answering n do for the current hunk?
You select only the title hunk. What should the cached diff show?
Which prompt response shows available help?
After committing only the title, what happens to the unstaged footer?