GIT restore last detached HEAD

In Sourcetree, you can do this using the GUI.

First find the "lost" commit by looking for a message in the Command History (view:Show Command Output). It will probably be in the command "Switching Branch" after the commit that you lost. In that message, hopefully you'll see the commit comment with a 1234567 commit ID.

Take that Commit ID to next step.

Hit the "Branch" button in the top toolbar and you should get a dialog "New Branch" where you can specify a certain commit. Put that Commit ID in there, specify a new branch name, hit Create Branch and you should get a new branch with your lost commit!

enter image description here


If you type git reflog, it will show you the history of what revisions HEAD pointed to. Your detached head should be in there. Once you find it, do git checkout -b my-new-branch abc123 or git branch my-new-branch abc123 (where abc123 is the SHA-1 of the detached HEAD) to create a new branch that points to your detached head. Now you can merge that branch at your leisure.

Generally, if you check out a branch after working on a detached head, Git should tell you the commit from the detached head you had been on, so you can recover it if you need. I've never used SourceTree, so I don't know if it relays that message. But if it did display that message, then you should be able to use that to find the commit, and again use git checkout -b or git branch to create a branch from that commit.

Tags:

Git