将光标移到/点击文章中的句子上,可以查看译文。      显示繁体中文内容    显示简体中文内容

How do you roll back (reset) a Git repository to a particular commit?
你如何回滚( 复位) Git存储库和一个特定的提交?

This question already has an answer here :

I cloned a Git repository and then tried to roll it back to a particular commit early on in the development process.everything that was added to the repository after that point is unimportant to me so i want to omit all subsequent changes from my local source code.

However, when i try to roll back in the GUI tool it doesn't update my local file system - i always end up with the latest source code for the project.

What's the correct way to just get the source for a repository as of a particular commit in the project's history and omit all later updates?

时间:


git reset --hard <tag/branch/commit id>


Notes :

  • git reset without the --hard option resets the commit history, but not the files.with the --hard option the files in working tree are also reset.( credited user )

  • If you wish to commit that state, so remote repository also points to rolled back commit do :git push <reponame> -f( credited user )

Update :

Because of changes to how tracking branches are created and pushed i no longer recommend renaming branches.this is what i recommend now :

Make a copy of the branch at its current state :


git branch crazyexperiment

(The git branch <name> command will leave you with your current branch still checked out. )

Reset your current branch to your desired commit with git reset :


git reset --hard c2e7af2b51

(Replace c2e7af2b51 with the commit that you want to go back to. )

When you decide that your crazy experiment branch doesn't contain anything useful, you can delete it with :


git branch -D crazyexperiment

It's always nice when you're starting out with history-modifying git commands (reset, rebase) to create backup branches before you run them.Eventually once you're comfortable you won't find it necessary.if you do modify your history in a way that you don't want and haven't created a backup branch, look into git reflog.Git keeps commits around for quite a while even if there are no branches or tags pointing to them.

Original answer :

A slightly less scary way to do this than the git reset --hard method is to create a new branch.let's assume that you're on the master branch and the commit you want to go back to is c2e7af2b51.

Rename your current master branch :


git branch -m crazyexperiment

Check out your good commit :


git checkout c2e7af2b51

Make your new master branch here :


git checkout -b master

Now you still have your crazy experiment around if you want to look at it later, but your master branch is back at your last known good point, ready to be added to.if you really want to throw away your experiment, you can use :


git branch -D crazyexperiment

...