How can I recover a lost commit in Git?

First, got "your branch is ahead of origin/master by 3 commits" then my app has reverted to an earlier time with earlier changes.

How can I get what I spent the last 11 hours doing back?


git reflog is your friend. Find the commit that you want to be on in that list and you can reset to it (for example: git reset --hard e870e41 ).

(If you didn't commit your changes... you might be in trouble - commit early, and commit often!)


First all what is HEAD ?

HEAD is a simply a reference to the current commit (latest) in the current branch.
There can only be 1 HEAD at any given time.

If you are not on the latest commit - meaning that HEAD is point to a prior commit in history its called detached HEAD.

在这里输入图像描述

Few options:

git checkout

git checkout <commit_id>

git reflog

You can always use the reflog as well

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

在这里输入图像描述


git reset HEAD --hard <commit_id>

"Move" your head back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts, if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7)
    you can also use the git rebase --no-autostash as well.

  • git checkout

    git checkout -b <new branch> <commit_id>
    git checkout HEAD~X // x is the number of commits t go back
    

    This will checkout new branch pointing to the desired commit


    Here is a general schema of what can be done.

    在这里输入图像描述


    Another way to get to the deleted commit is with the git fsck command.

    git fsck --lost-found
    

    This will output something like at the last line:

    dangling commit xyz
    

    We can check that it is the same commit using reflog as suggested in other answers. Now we can do a git merge

    git merge xyz
    

    Note:
    We cannot get the commit back with fsck if we have already run a git gc command which will remove the reference to the dangling commit.

    链接地址: http://www.djcxy.com/p/60.html

    上一篇: 硬。 没有找到fsck,没有在reflog

    下一篇: 我怎样才能在Git中恢复丢失的提交?