Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add changes to commits in the middle in Git

Tags:

How to add the new changes to the commits which are in the middle, I mean not adding to the top commit.

git log commit1 <--- HEAD commit2 commit3 

How to add the changes directly to commit3, without removing commit1 and commit2 and then adding changes to the commit3.

Do I need to use stash?

If possible, please provide the link.

like image 961
viru Avatar asked Aug 04 '11 14:08

viru


1 Answers

You have to do an interactive rebase. Read the help page for git rebase for the details. The short answer is that you'll go ahead and commit your "middle" changes as usual, then run git rebase -i HEAD~4. It'll bring up a list of the last 3 commits in a text editor. Simply reorder the commits where the newest commit is put in the middle, and then save and exit the editor. Git will then attempt to rebuild the history in the new order. It might stop with conflicts. If so, fix them like you would for a merge conflict and then run git rebase --continue after they are all fixed and added. It tells you all this when you have a conflict, so just read the error messages and you should be fine.

EDIT: actually, it looks like you want to edit an existing commit. In that case, when the editor comes up, move your new temporary commit to be next to commit3 and then change the command to "squash" from "pick":

pick 123456 commit3 squash 541343 tmpcommit pick 654321 commit2 pick 431523 commit1 

EDIT2: if the branch and commit1, commit2 and commit3 are already public, then you shouldn't be rebasing. Then again, you shouldn't be modifying commits anyway, so the whole question would be moot. I'm assuming that this is a private branch or one that is expected by others to be rebased and rewound.

like image 129
siride Avatar answered Oct 05 '22 23:10

siride