Book Your Free Call

How To Revert Multiple Commits In Git?

Tim Mouskhelichvili
Tim Mouskhelichvili
2 minutes to read

While working with Git, a situation may occur when a developer wants to revert multiple commits at once. This operation is possible and can be achieved in various ways. The easiest way to revert multiple commits is to use the git reset command.

To revert multiple commits, use the git reset command with the last commit's hash that you want to preserve, like so:

bashgit reset --hard <hash>

This article will explore different ways of reverting multiple commits at once.

Let's get to it 😎.

git revert multiple commits

How to revert multiple commits with git revert?

One way to uncommit multiple commits is to use the git revert command with the --no-commit option.

To revert multiple commits, type this command for each commit you want to remove:

bashgit revert --no-commit <hash>

Note: You can find the commit's hash by going into the reflog, using the git reflog command.

Then, commit and push your changes.

However, note that this command will not work with merge commits.

How to revert multiple commits at once with git reset?

To remove multiple commits at once, use the git reset command. It will even work for merge commits.

Note: The git reset command is a tool for undoing changes.

1. To revert the last two commits, type:

bashgit reset --hard HEAD~2

Note: HEAD refers to the lastest commit of the active branch.

2. To revert the last three commits, type:

bashgit reset --hard HEAD~3

3. For reverting to a specific commit's hash, type:

bashgit reset --hard <hash>

If you have already pushed to a remote, you will get a fast-forward error because your local history diverges from the remote history.

To fix this error and push your changes to the remote, use:

bashgit push -f

🚨 However, use git push --force with extreme caution because it can result in lost work if you are not careful. 🚨

How to revert multiple commits in the middle of the history?

To revert multiple commits in the middle of the history, use an interactive rebase.

  • Find the last commit's hash containing all the commits you want to remove.
  • Start an interactive rebase session with git rebase -i <hash>.
  • In the interactive rebase edit screen, remove the commit lines you want to remove.
  • Save and exit the edit screen.
  • Use git rebase --continue to end the rebase.

Note: You can also abort the rebase and start over.

Final thoughts

Reverting multiple commits may be easy, but you still need to be careful because you can lose valuable work if you are not cautious.

git revert multiple commits

Here are other Git tutorials for you to enjoy:

Comments (0)