Commit parts of a file in Git

Sometimes when you are about to commit your changes to Git, you realize that you should have split the changes in a few different commits instead of just one unorganized sloppy commit. Since some files will have overlapping commits, you no choice but to combine all changes into a single commit… Wrong!

In Git you can commit only selected parts of a file by staging your changes with:

git add -p <file>

This command will prompt you for each chunk of changes and then stage them.

When you’ve staged all changes that will be for a commit, you might want to test if this commit will run independent from the rest of the unstaged changes.

Stash away all unstaged changes with:

git stash -k

Run all your tests. If it’s OK, commit. Then bring back the changes with:

git stash pop

Now you have no excuse for sloppy commits!

Leave a Reply

Your email address will not be published. Required fields are marked *