gitgit-branchgit-detached-head

Restoring accidentally lost commit due to detached Head


I lost my code after switching to another branch (thought that I pushed it, but head was detached)

I switched from master to origin/somebranch Did some work there Then I had to quickly fix something in master, so I did git add -A git commit -m "some commit" git push git checkout master

I did it pretty fast, so I didn't read the message about head being detached... So a result when I switched back to somebranch, my changes were not there... Are my changes lost or there is a way to restore it?


Solution

  • No, your commit is not lost, it would be at this point unreferenced by any branch (and, as such, candidate for garbage collection) but the reflog keeps a reference on it for some time (90 days by default, but you can check your config entry gc.reflogExpire) so you'll be able to recover it.

    How? First possible method :

    Condition : only if your terminal is still open with the output of previous operations.

    If so, you'll be able to easily spot the hash of your commit :

    git commit -m "Useful message here"
    [master ec470f4] Useful message here
     1 file changed, 1 insertion(+), 1 deletion(-)
    

    Just recreate a branch at this point :

    git checkout -b recovered-branch ec470f4
    

    If, for any reason, you do not have this opportunity (terminal closed, did a clear in the meantime, anything), no worries :

    Second method, reflog

    git reflog
    

    lists all previous positions of HEAD, so just get the commit hash you want there and use the same command to recreate your branch.