git reset
only applies to the current branch, so if you want to perform it on a separate branch, just create one and check it out. For example using git checkout -b new_branch_name
. This will create a branch that points to the same commit as before. Then you can perform your git reset --hard
without affecting the original branch you were on.
Now if you have used git reset --hard
and you don’t have a backup branch pointing to the original commit, you can still recover it. Git luckily won’t delete commits that are lost but will keep them around until the repository is garbage collected. So you have a good chance on recovering.
The first thing you should check is the reflog using git reflog
. It will give you a log of what HEAD
previously pointed at. At some point you should see an entry like this:
b3db916 HEAD@{n}: reset: moving to b3db916
This was the result of your git reset --hard b3db916
. Now the entry immediately below it is the state before the hard reset. So if you look at the hash on the very left, that should be your commit you want to recover. You can verify that using git show <hash>
. Btw. instead of specifying the hash, you can also use git show HEAD@{n+1}
(n+1
is the number after the number of the reset entry). If it isn’t the commit you are looking for, try other ones around to see whether you can find it.
If you have found the commit, you can just create a new branch that points at it using git branch new_branch <hash>
or git branch new_branch HEAD@{n+1}
.
If you can’t find the entry in your reflog (which is somewhat unlikely but possible), you can also try to recover lost objects using git-fsck
.