DEV Community


Edit a previous commit during an Interactive Rebase

Andrew Casarsa
software engineering
・2 min read

Before starting make sure you commit and push your code (see rebase --abort and hard reset in case you mess up and just want to start over). You should also create a backup git branch backup-your-branch-name


  1. git fetch

  2. git rebase --interactive HEAD~20 NOTE: on HEAD~20 this is the number of commits into the past you will look at while inside the --interactive rebase.

  3. Locate the commit in question

  4. All commits will have the word pick next to them in your text editor. Change the pick next to chosen commit to edit. Save and exit. (in Nano this is ctrl-x then Y then enter). NOTE: Now if you type git log you will see that you are sitting at the place in time right after you made the commit you want to change.

  5. git commit --amend will allow you to make changes to the previous commit

  6. Enter git log to check and make sure your target commit is at the top of the log list.

  7. Make your changes and run git add . to add those changes.

  8. Run git commit --amend to open the commit message in your editor, save it, and exit. This will squash your changes into the target commit. This will change the commit hash code.

  9. Run git rebase --continue and you should get the message Successfully rebased and updated refs/heads/<your_branch_name>.

  10. Check to make sure everything seems normal and then do git push -f to replace the remote copy of your branch with your fixed local copy.


How is fetch different from pull?

git fetch is the command that tells your local git to retrieve the latest meta-data info from the original (yet doesn't do any file transferring. It's more like just checking to see if there are any changes available)

git pull on the other hand does that AND brings (copies) those changes from the remote repository.

What is a rebase?

git rebase rewrites the commit history in order to produce a straight, linear succession of commits. Basically what it does is take the fetched commits and your commits and reorders them in the correct way (it is actually creating new commits to do that but for a basic understanding we won't get into any of that).

The reason we do a rebase is so that when you push up your code and merge it with the main or master branch you won't rewrite anything anyone else added before you.

Tried this and it got totally f'd?

First, try to do git rebase --abort this will cancel the rebase and let you start over. If this doesn't fix your issue you can do a hard reset.

A hard reset will replace your local branch with the branch that is stored remotely. !!!BE CAREFUL!!! only do this if you are 100% sure your local branch doesn't have important new info you don't have stored remotely. You can make a backup of your branch if you're concerned. git reset --hard origin/<your-branch>

Discussion (0)