Rajat Kapoor
Rajat Kapoor's dev blog

Rajat Kapoor's dev blog

Amend an old git commit using git rebase

Amend an old git commit using git rebase

Rajat Kapoor

Published on Jun 3, 2021

2 min read

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

  • Use git log to 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 6070a615f127fb0fe410db454251d7279c0eaa2c
git log

carbon (1).png

  • 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

carbon (4).png

  • 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 fixup! commit.

Note that this is where we deviate from the regular process of commiting

carbon (3).png

  • if you check your git log, you will see that a !fixup commit is created at the top

carbon (6).png

  • 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.

carbon (8).png

  • 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

That's it

For more regular tech content including updates on many of my interesting web dev side projects, follow me on twitter

Did you find this article valuable?

Support Rajat Kapoor by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this