简体   繁体   中英

How to undo a Git master branch checkout

First, yes...I'm an idiot. I was using Git without an understanding of it and now I'm pretty sure I've lost most of my work. I had somehow created what looked like a branch in the graph but may not have been an actual branch. My main work was actually not in the master branch - something I was going to resolve...at some point. I had just finished resolving some nagging issues in my code, staged everything and committed it when I decided it was time to try to fix the issue with the master branch actually being old code. I checked out the master branch, not realizing exactly what that meant (because, I'm a moron) and now I can't find any hint of my main code to revert to. I'm using Visual Studio Code and that's what I used to check out the master branch. I've also used the Git GUI and I can't find anything about the other branch in there either. I just never though Git would leave me in a situation where that code would be gone so I didn't think much of checking out the master branch. But, now, I'm afraid to do anything. Is there some way to see the other branch or revert to my main code?

(copied from comments, edited a bit for answer-ness)

Step 1 in this case is: don't panic! You committed , so the code should still be in there. It's now a matter of finding it.

The first place to look is at git reflog output. I suspect (and commentary followup confirms) that what you did was make a commit using what Git calls a "detached HEAD". These commits are immediately abandoned when you git checkout some branch—but like abandoned commits in general, they're recoverable for at least 30 more days by default.

From a command-line interpreter— bash or cmd.exe or powershell or whatever—run git reflog . Look closely at each commit message. If any of those are the stuff you committed, grab the abbreviated hash ID on the left, then use:

git branch newname hash

to create a new branch name for that hash ID. The new name now gives you access to the commit, and any earlier commits as well, that you had made in that "detached HEAD" mode. It should show up in all the graphical user interfaces now too, such as Git GUI and Visual Studio Code (though I have never used VS myself).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM