Selectively stage part of a new file in git

Posted by: on

Problem

You have a completely new file to add (stage) into your repository but you want to add only a part of the new file to this commit.

Issue

If you simply use git add file.txt the whole file is added.

If you try git add -p file.txt you find git just ignores you.

Solution

Add the file in two steps:

1
2
git add -N file.txt
git add -p file.txt

This allows you to selectively add files just as you would for a regular patch operation (briefly, edit the file presented by the add -p command and ‘comment’ lines that are not to be added at this time by preceding with a # character).

Discussion

The patch operation needs something to patch but since file.txt is not known to git until it is added we have a chicken and egg situation: We don’t want to add the whole file, but until we add something git doesn’t know how to construct a patch.

By issuing the git add -N file.txt command we tell git that we intend to add a file called file.txt some time in the near future. git adds an empty file to the stage cache. Once this empty file exists git has something against which a patch can be created and the git add -p file.txt command works as expected.