How can I recover from an erronous git push -f origin master?

Git generally doesn't throw anything away, but recovering from this may still be tricky.

If you have the correct source then you could just push it into the remote with the --force option. Git won't have deleted any branches unless you told it to. If you have actually lost commits then take a look at this useful guide to recovering commits. If you know the SHA-1 of the commits you want then you're probably OK.

Best thing to do: Back everything up and see what is still in your local repository. Do the same on the remote if possible. Use git fsck to see if you can recover things, and above all DO NOT run git gc.

Above above all, never use the --force option unless you really, really mean it.


If you know the commit hash, it's easy, just recreate your branch.

5794458...b459f069 master -> master (forced update)

Delete the remote branch:

git push origin :master

then recreate your branch with the following commands:

git checkout 5794458
git branch master
git push origin master

The solution is already mentioned here

# work on local master
git checkout master

# reset to the previous state of origin/master, as recorded by reflog
git reset --hard origin/master@{1}

# at this point verify that this is indeed the desired commit.
# (if necessary, use git reflog to find the right one, and
# git reset --hard to that one)

# finally, push the master branch (and only the master branch) to the server
git push -f origin master