简体   繁体   中英

How to revert the local repo back to the previous commit after git pull?

Suppose git pull command advances my local repo by several commits to match the remote repo and I want the local repo goes back to the commit id before git pull. In other words, I want to undo everything I get from git pull. Which command should I use?

To switch the branch back, simply checkout the Git commit listed in the output of the pull request:

$ git pull
Updating d5c40ea5e..29f1ae2b3
Fast-forward
 README.md                                             | 15 +++++++++++++++
 gradle.properties                                     |  2 +-
 2 files changed, 16 insertions(+), 1 deletions(-)

Note the d5c40ea5e this updated from. Simply check out this branch, and the code will be back to what it was before the pull request.

$ git checkout d5c40ea5e
Note: switching to 'd5c40ea5e'.

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 switching back to a branch.

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

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at d5c40ea5e Update code to be super awesome

I don't know of a silver bullet way of doing this, but with some minor detective work it is not difficult. First run git log from the local branch in question. You might see a merge commit at the HEAD of the branch. This would be the case if your pull strategy were merge. Or, you might see some number of new commits in the event that your branch were fast-forwarded. In either case, simply find the SHA-1 hash of the commit before the contents of the pull, and then hard reset to it:

# from your local branch
git reset --hard <SHA-1 of earlier commit>

Note that if your Git pull strategy be rebase, you have another problem. Now you can't simply just reset to an earlier commit, because potentially the pull has already rewritten your history. Cleaning up in this case might be a lot more work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM