Last Updated: February 25, 2016
·
3.046K
· jedschneider

git checkout (and add) -p

removing changes

checkout is a multi use command in git. the most common of course is switching branches, but it can also be used to 'reset' changes back to the state of the file on HEAD. so, if you want to reset the file to the last versioned state you can do:

git checkout myfile

and all your changes are gone.

getting a previous version of a file

But you can also use checkout to check out a file from a previous commit in the current branch.

git checkout production myfile

checks out myfile from the HEAD of the production branch and adds it to the index (aka already 'added').

Better than :/console

One of the less known and I think really useful strategies is to use the -p flag to checkout or stage only parts of files that interest you. First let me give an example of how I use it before committing.

Let's say that you've just spent an hour tracking down a strange issue in javascript and have been using console.log statements to inspect state along the way. The actual fix is just two separate lines of code but you've added another 10 debug statements to the the code base that you obviously don't want to commit. You can use the -p flag to remove the log statements before adding the files to the index. I find it faster and more convenient than searching for the statements in my text editor.

git checkout -p myfile.js

will give you an interactive prompt that will ask you, one chunk at a time if you want to add that chunk. If the chunk is too broad, hit 's' and it will split the chunk into smaller sections. Saying yes ('y') will remove the change, no will keep it.

- console.log "I'm a real boy"
+ console.log "I'm not a real boy"
Apply this hunk to index and worktree [y,n,q,a,d,/,e,?]? 

Alternatively, if you want to keep the log statements around (maybe you are not done debugging, but found something worthy to commit) you can you use:

git add -p myfile.js

to stage only the sections you want to †he index and leave your console statements uncommitted but still in the code. This idea takes the most to wrap my head around, but is really very useful on a daily basis once you understand how the index works.

Double Rainbows

The following strategy is the basis for me writing this tip today because its the first time I've used it in this context. Lets say that you have changed a file and made a commit and need to revert some changes but keep others from a previous commit, in this case 6fb7e99:

git checkout -p 6fb7e99 myfile

brings up an interactive prompt that will allow you to add only certain hunks from the previous file directly to the index. Saying yes reverts the change, saying no keeps the change as you have it in the existing file. Once you are done reverting your changes, your file is already on the index and ready to:

git commit -m "reverted some changes"