3

I rolled back to previous commit using git checkout "commit number1". Then i didn't realize i was on commit and not on any branch so i made changes here and committed the code in "commit number1". Now i switched to feature branch. feature/branch1 and i don't see any code. If i switch back to "commit Number1", i don't see the code there either. Am i detached from anything?

$ git checkout 49da8b4d431

Note: checking out '49da8b4d431'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

How can i recover the code? WHere did my code go?

zachandcode
  • 151
  • 3
  • 10

2 Answers2

6

Type git reflog which will show you a list of all recent commits. Find the commit whose message is "commit number1", then record the SHA-1 hash of this commit (which will look something like a random alphanumeric string of 7 characters, e.g. s73nd9a).

To bring this commit into your feature branch, one option would be to use git cherry-pick. Try the following:

git checkout feature/branch1
git cherry-pick s73nd9a

This will apply the single commit you made while in the detached head state. Keep in mind that a cherry pick is essentially a merge of one commit, and as such you might get conflicts.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
3

git reflog will show you the history of your HEAD. Look at it to find the SHA of the commit you made on top of "commit number1". When you know the SHA you can cherry-pick it where you need it to be.

Paul
  • 13,042
  • 3
  • 41
  • 59