Break up multiple changes into separate commits with git?

Git

Git Problem Overview


If I have made multiple sets of changes to a large file, is it possible to split those into separate commits using git?

Git Solutions


Solution 1 - Git

You want git add --patch (documentation), which will allow you to select which changes to stage.

Solution 2 - Git

Yes, you can -- use git add -i to select which hunks you want to stage for each commit. You can get documentation by running git help add and scrolling to "Interactive Mode".

Solution 3 - Git

One more option which I constantly use is just because i forget about the patch option :):

Say you have updated files: aaa.txt, bbb.txt, ccc.txt and you want to push the aaa.txt file in the first commit and then bbb.txt and ccc.txt in the second commit:

step 1:
--------------------
git add aaa.txt
git commit -m "Added first file"
git stash
git push

step 2:
--------------------
git stash pop
git add -A
git commit -m "Added the rest of the modified data"
git push

Might be a little more verbose, but in my opinion I it gives a bit more control.

Cheers!

Solution 4 - Git

Williams answer is perfectly valid. But sometimes it is easier to do things by hand. For example if you accidentally updated some third-party library with a lot of files before committing the changes you previously made. With git add -p (same as --patch) you would need to walk through all of this files. So in this case it is much more convenient to just stage the file you want to commit and do a second commit with all of the other changes:

> git add /path/to/your/file.txt
> git commit -m "my commit message"
[master a0c5ea6] my commit message
1 file changed, 2 insertions(+), 1 deletion(-)
> git add --all
> git commit -m "updated library xyz"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarkdorisonView Question on Stackoverflow
Solution 1 - GitWilliam PursellView Answer on Stackoverflow
Solution 2 - GitAndrew AylettView Answer on Stackoverflow
Solution 3 - GittheVoogieView Answer on Stackoverflow
Solution 4 - GitAvLView Answer on Stackoverflow