Have you ever been hammering out some code, making commits, only to realize you’ve botched something up a few commits ago? Happens to me quite often and I just realized there is an easy way to fix it via an interactive rebase.
As long as you haven’t pushed your commits upstream, follow these steps and you’ll be golden. If you have pushed, just make your fix in a new commit because the steps below will result in a new sha being generated for the commit you’re modifying.
- Save or stash your existing work.
git logto find the first few characters of the ID of the commit you’d like to edit.
- Begin the interactive rebase by running
git rebase -i ID^.
- Find your commit in the list you’ve been presented and change the word ‘pick’ to ‘edit’. Save and quit the editor.
- Make the necessary changes to your files.
git commit -a --amend.
- Proceed with the rebase by running
git rebase --continue.
- Resolve any conflicts created by your new changes.
- Re-apply any stashed changes.