Not currently on any branch + git commit + checkou

2020-02-02 06:41发布

问题:

I was not currently on any branch when I commited my changes. I didn't really notice the message and checked out another branch.

How can I retrieve my changes? I can't merge or checkout, since there is no branch to merge from.

回答1:

You can use git reflog to get the commit hash of the commit that you did while in "no branch" ( a detached HEAD) and merge that in to the branch that you are currently in ( master maybe)

Something like git merge HEAD@{1}

You can also git rebase -i and "pick" the commit you want from the reflog.



回答2:

I was in a similar state after committing some work:

Lilith:Manager KelSolaar$ git status

Not currently on any branch.

I issued a git log to see my last commit hash:

Lilith:Manager KelSolaar$ git log

commit 49984303037e970d637161c3154b7fd7d6ae3a43 Author: KelSolaar Date: Wed Oct 5 22:41:31 2011 +0100

Introduce new "QObject" components category and rename existing ones to "Def

I then checked out my master branch:

Lilith:Manager KelSolaar$ git checkout master

Previous HEAD position was 4998430... Introduce new "QObject" components categorie and rename exising ones to "Default" and "QWidget".

Switched to branch 'master'

And I finally merged using the commit hash:

Lilith:Manager KelSolaar$ git merge 49984303037e970d637161

Updating 141bc69..4998430

Fast-forward

src/manager/component.py | 2 +-

...



回答3:

git checkout - will switch you back to the previous branch:

Thu Feb 21 12:50 AM /src/test ((08f84f4...)) $ git checkout master

Warning: you are leaving 1 commit behind, not connected to
any of your branches:

  08f84f4 Fix everything

Switched to branch 'master'

Thu Feb 21 12:50 AM /src/test (master) $ git checkout -

HEAD is now at 08f84f4... Fix everything

Thu Feb 21 12:50 AM /src/test ((08f84f4...)) $


回答4:

Your commit isn't gone, you can recover by asking git to show you the hidden commits, and put them back in a temporary branch.

See this answer for instructions.



回答5:

Use "git reflog" it shows the commit hashes of the results of your git command history. You can then "git co hash" and when you've found the right one, set/make a branch for it.



回答6:

You're never "not on any branch". You might have been on the branch called master, but you WERE on a branch when you committed. So that commit is SOMEWHERE.

Use git log to look at history. You can use git reset to go back in time (including, optionally, leaving the changes in your working directory).



标签: git commit