Amend an old git commit using git rebase
We can use
git commit --amend to make changes to our previous commit. But have you ever wondered what is the best way to fix an issue with an older git commit? Follow along and we'll learn this amazing git hack
Here is how you can do it
git logto find the commit that you wish to fix. Copy the commit's hash as we will need it later. For example, if you want to fix the commit with the message
Added magic to code, copy it's hash
- Make changes to the files you wish to fix and stage them for committing using
git add <file paths>. For example, if you made changes to
index.js, add it using:
git add index.js
- Now instead of using the regular commands to commit, use
git commit --fixup=<hash of the older commit that we copied in step 1>
This will create a
Note that this is where we deviate from the regular process of commiting
- if you check your
git log, you will see that a
!fixupcommit is created at the top
- You can now automatically squash the fixup commit with the older commit using rebase with autosquash
$ git rebase -i <old commit hash>~1 --autosquash
- In the interactive rebase editor, you will see that the fixup commit would have automatically moved next to the old commit that we wanted to fix.
- Proceed with the rebase by closing the editor (as you usually do with a regular rebase). Resolve the merge conflicts if any.
You'll see that the older commit is updated with the changes you made in the fixup commit
For more regular tech content including updates on many of my interesting web dev side projects, follow me on twitter
Interested in reading more such articles from Rajat Kapoor?
Support the author by donating an amount of your choice.