21

Let's say I make a number of commits, let's call them 1, 2, 3, 4, 5, and 6 (hashes).

Let's say I'm on a commit with hash 6. All I want to do is to go back to hash 3, make it so the state of my codebase is as it was when I committed to hash 3 as if the other commits never happened.

When I look at answers like this, it seems like everybody has a different answer. reset, revert, rebase? I'm not even sure that I know the difference between those three words in English.

I just want to be at a previous commit. Can someone tell me how to do this?

ecm
  • 2,583
  • 4
  • 21
  • 29
Alexander Kleinhans
  • 5,950
  • 10
  • 55
  • 111
  • 2
    related: https://stackoverflow.com/questions/28166547/what-are-the-differences-between-revert-amend-rollback-and-undo-a-com – jub0bs Aug 31 '16 at 22:48
  • `reset` means to reset your repo so it looks like it did at a different commit (history and all). 'revert' means to add more commits to make the code look like it did at a different commit, but the history is different (the history includes the old state and the path back to the different state). `rebase` doesn't change the code at all, but just changes the history. – William Pursell Aug 31 '16 at 22:52
  • Also http://stackoverflow.com/questions/4114095/how-to-revert-git-repository-to-a-previous-commit – Christoffer Hammarström Aug 31 '16 at 23:00
  • Revert allows you revert to a particular commit, losing everything between HEAD and that commit. Rebase allow you to cherry pick commits you want to drop - https://norman-lm-fung.medium.com/git-revert-vs-git-rebases-e9307013f152 – user3761555 Mar 27 '21 at 15:24

2 Answers2

25

If you have already pushed your branch somewhere or someone pulled from you, your only option is to git revert $COMMIT....

This will create a commit that undoes whatever you've done in commit(s) $COMMIT....

For example, to revert the last three commits:

git revert HEAD~2..HEAD

If you have kept your commits entirely local and private, you can simply git reset $COMMIT.

This will move your branch pointer to $COMMIT so the branch no longer includes the following commits.

Depending on the state of your index and working tree, you might want any of the options git reset --soft $COMMIT or git reset --hard $COMMIT.

For example, to reset your branch to the commit before the last three:

git reset HEAD~3

git rebase does not sound like what you want.

You use it when you want to copy or "move" some commits from one commit that they are based on, to be based on another commit (another base), hence "rebase".

Christoffer Hammarström
  • 27,242
  • 4
  • 49
  • 58
-1

How about this way:

  1. you create a branch for hash 3.

  2. create a PR or merge this branch to master(hash 6)

  • 2
    If he wants to go to commit 3, this will not work if he added files between 3 and 6. – Xys Aug 08 '17 at 09:48