Git: How to amend the second to last commit
You have most probably heard abour or used git commit --amend
. It allows you to modify the most recent commit by changing its message or adding new changes without creating a new commit.
It is useful for typos, quick little fixes, or anything that you forgot to add. But what happens when you want to amend your changes to the commit before that. Or the one before that. Or the one before that and so on.
The solution
The solution lies in git rebase
1
git rebase -i HEAD~3
This will open a text file (or VSCode’s interactive rebase) where you can make changes to your commits. You can specify how many commits you want to “edit” by changing the number (HEAD~5
for example). This is how the file will look like:
1
2
3
pick 4d44ba0 The commit you want to change
pick e23ed49 Some other commit
pick z195e00 The commit with your changes/fix
First, we need to reorder the commits. We put the commit with the fix z195e00 right below the commit that needs fixing 4d44ba0
. Second, instead of pick
we change the word to squash
if we want to change the commit message or fixup
if we want to keep the commit message as it is.
1
2
3
pick 4d44ba0 The commit you want to change
fixup z195e00 The commit with your changes/fix
pick e23ed49 Some other commit
When we close the file the changes will be saved and we can continue on with our work.
Conclusion
Git rebase is a powerful feature that allows you to rewrite commit history, clean up mistakes, and keep your Git repository organized. By using interactive rebase, you can amend older commits, combine multiple commits, or even reorder them as needed. However, be cautious when rebasing shared branches, as it rewrites history and may cause conflicts for collaborators.