How to go back to previous commit without losing last commit in Git?

Here is what I want to do. I want to go back to 2 commits before, bring back the files that changed in that commit as a new commit maybe. But I do not want to lose my last commit. My last commit has some mistakes in the code but I would like to keep that one for now.

I read some documentation but none made it clear about what happens when you reset your head. Do you lose all the commits up until the one that you are resetting to (going backward) for example?

  • Having trouble working with a Git repository
  • Strong access control for Gollum?
  • What if the owner of some repository on github has stopped working on some project but I want to contribute to it?
  • Can't install GitHub on Windows 7 (64 bit)
  • Delete all tags from a Git repository
  • How to make git send an email in case of unresolved merge
  • I am trying to understand how all this works but I am rather confused about git revert, reset and checkout commands.

    I realize that I should have stashed the last commit instead of committing, but that is another story for now.

  • “${1-}” vs “$1”
  • Git for Websites / post-receive / Separation of Test and Production Sites
  • Using bundler, how do you unpack a gem installed via a git repository?
  • Git: How to fix commit during rebase
  • What to do with unpushed git commits after mvn release:perform
  • TortoiseGit icons overlays icons on desktop
  • 2 Solutions collect form web for “How to go back to previous commit without losing last commit in Git?”

    revert makes a new commit that reverts changes made by an older commit. reset --hard changes the HEAD of the current branch to the specified commit. checkout switches the working copy to the specified branch or commit.

    When you reset a branch to an older commit the newer commits are lost if they are not parts of other branches or ancestors of tags (they are still accessible via reflog though).

    It is not clear what do you need to do, the most probable solutions are revert (to fully revert an older commit or series of commits) and rebase -i (to change an older commit or delete it from the history).

    If you want to go back, say 2 commits previous, you can just do git checkout HEAD~2. This will get you all as it was then. If you were on branch master, git checkout master will bring you back to the present. If, however, you want to keep the current state but start a new developemnt branch there, git checkout -b HEAD~2 will start a new branch there. In case you want to rewind master but not loose your current, unfinished/broken work, do

    git branch wip           # New branch ends a current tip
    git reset --hard HEAD~2  # Old branch rewound, get files from then
    Git Baby is a git and github fan, let's start git clone.