All How-Tos
Intermediate

How to Commit Only Selected Lines in Git

Learn how to commit selected lines while leaving other edits for later.

Stage Selected Changes

Start with no changes staged. If necessary, unstage files first; their working contents will remain unchanged.

Use patch mode to choose which changes from a file should enter the Index.

git add --patch -- <file>

Choose Chunks or Individual Lines

Git groups nearby edits into chunks and asks what to do with each one:

  • y: stage this chunk.
  • n: leave this chunk out.
  • s: split the chunk into smaller parts, when possible.
  • e: open the patch in your editor to select individual lines.

In the patch editor:

  • To leave out an insertion, remove its added line (beginning with +).
  • To leave out a deletion, replace that line's leading - with a space.
  • For a block that replaces several lines, keep the deletion lines and edit the added (+) lines to contain the text you want staged. To defer one replacement within the block, put its original text back on the corresponding added line. This keeps adjacent lines in the right order.

Keep the patch headers and existing context lines intact, then save and close the editor. Editing the patch changes the Index while leaving your working file unchanged.

Review and Commit

  • Review the Index: Check that the staged diff contains exactly the change you want to commit. Inspect the complete staged file as well, especially after editing a patch by hand.
git diff --cached
git show ":./<file>"
  • Create the Commit: Use git commit without a file argument or -a, so it commits the Index you just reviewed. Those options could otherwise include edits you left out.
git commit -m "Describe the selected changes"
  • Check the Remaining Changes: The other edits are still in your working file. Review them and repeat the selection process when you are ready for the next commit.
git diff -- <file>

Start with a New File

Before using patch mode on an untracked file, mark it with --intent-to-add. This makes the file available for patch selection without staging its contents. Then follow the selection and commit steps above.

git add --intent-to-add -- <new-file>

Considerations

  • Running git add -- <file> after partial staging stages the file's full current contents. Use patch mode again to add more selected changes.
  • Tests run in your working tree see both staged and unstaged edits. Check that the selected change also works without the edits you are leaving for later.
  • Line selection applies to text changes. Binary files must be staged as a whole.