Have you ever been working on a project, ran a git pull
only to realise you've majorly messed up? Now all your code has been overwritten with whatever was in your remote repository - and sometimes this isn't what you want. In times like this, it's easy to panic, but fortunately there are a few ways to revert your code back to its old state and undo the git pull
.
First things first, make a copy of your project in case you cause things to get worse. Also note that these commands will cause you to lose all uncomitted changes - so a backup can help you save that stuff before you continue. At least then, you'll have the version you currently have. After you've done this backup, you'll want to get a list of all your commit history. You can do this by running git reflog
:
git reflog
This will generate a list that looks like this:
648e314 (HEAD -> master, origin/master) HEAD@{0}: commit: Design refresh
b0168ee HEAD@{1}: commit: Minor CSS tweaks
514a02f HEAD@{2}: commit: Fixed extra curly brace
b432ba7 HEAD@{3}: commit: fixed border-radius
a707d13 HEAD@{4}: commit: fixed image border-radius
abf89a3 HEAD@{5}: commit: updated look and feel
Select the version you want to revert to. For example, if I wanted to revert to 'Minor CSS tweaks', I'd select the ID b0168ee
. Next, run the following command to revert your repository to that verson:
git reset --hard b0168ee
This is quite easy, and gives you a lot of control over which version you recover. However, another easier way to do this is to give a time. If you don't want to run git reflog
, you can run the following command to revert to the version of your repository as it was 30 mins ago, assuming your branch is master
. Note, if you have been working on a specific branch for a long time, this may revert you back quite far. In that case, you might be better using the previous method - but you should be fine if you have a backup. 😄
git reset --hard master@{"30 minutes ago"}
Top comments (2)
Okey but what if i pushed to master being on feature branch? Or even revert the push to remote (origin) master? Any differences between each one?
Not explained clearly
this is about undoing a git pull, not a git push