Reputation: 6918
Query is regarding git reset,
Stage 1: Now I would like to revert back to a specific commit using the below command provided no local changes are there.
git reset --hard <sha 1 of specific commit>
Query 1: How I could make the revert to a new separate branch?
Query 2: After some time, I would like to revert to Stage 1 state, taking back all commits which I discarded using
git reset --hard
. Is that possible?
Please suggest :)
Upvotes: 0
Views: 915
Reputation: 1035
Question 1: I suppose you would want to "Do" things after a specific commit[and there's a lot of commits below that specific commit].Assume this branch to be STAGE_1_BRANCH
If that's the case, you could do
git checkout -b temp sha_of_specific_commit
#do_things
#commit
Question 2: Now you would want to push back your recent commit to the STAGE_1_BRANCH just after the specific commit and followed by the other commits
git rebase temp STAGE_1_BRANCH
Upvotes: 0
Reputation: 387955
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
.
Upvotes: 3
Reputation: 8695
1 git checkout -b newbranch && git reset --hard sha
2 everything is possible. Do you want to reset the newbranch to the original state? Do the git reset. Do you simply want to get the original state at you working directory? Then git checkout stage1
Upvotes: 0