2

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?

Romain Valeri
  • 19,645
  • 3
  • 36
  • 61
John W
  • 151
  • 6
  • Check the below link, this would definitely help you https://stackoverflow.com/questions/10099258/how-can-i-recover-a-lost-commit-in-git – Yeshwin Krishna Jan 17 '23 at 08:14

2 Answers2

3

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.

Romain Valeri
  • 19,645
  • 3
  • 36
  • 61
2

Just check the reflof and find your commit and use that ID to create a new branch or move an already existing branch

git reflog
git branch -f some-branch the-id-of-the-revision
eftshift0
  • 26,375
  • 3
  • 36
  • 60