Skip to content

How to revert commits that have been pushed to a remote repository

Problem

Sometimes some changes get pushed to a remote repository by mistake. This can affect the other team members if your changes are corrupted or incomplete.

Solution

Let's say you have 3 commits like this

work 3 at 11 PM - ebdecf01d713f5ee898e0a290d0881776b247916

work 2 at 10 PM - b9df09cfe815411f0422e26d773d47a17040b08c

work 1 at 9 PM - 70414f297e46c5f6fc2a0ae03d677aa363d6f291

To check commit hash - just type git log in terminal

sh
git log

Commit 3 is the latest one, which is work 3

If we want to get rid of 2 commit work 3 and work 2 together, follow these below steps:

  • Step 1: Move to commit 1 which is work 1 by using this command
sh
git reset --hard <commit-hash>

Commit hash looks like this: 70414f297e46c5f6fc2a0ae03d677aa363d6f291

In the above-mentioned example, the command will be like this to move to work 1

sh
git reset --hard 70414f297e46c5f6fc2a0ae03d677aa363d6f291
  • Step 2: Force push it to the remote repo by using this command
sh
git push --force-with-lease

OR, if the above command doesn't work. Then, use the below command. Make sure to replace the remote and branch with your working repository.

sh
git push <remote> <branch> --force-with-lease

That's all. Problem solved!