Git Checkout reverted code to older commit, how to revert back?

I have been working on some code, which I use git to manage. Earlier, I used commit to save a version of my code that worked. I later decided to redo the code, since it needed some new features and was designed poorly. After I got it working, I did another git commit. After doing git log, I saw I was not on any branch. So, I did “git checkout master”. This brought be back to the version of my old code, with git log now showing my latest commit. This was A LOT of work, so I wanted to know if there was any way to undo what I did, and get back my latest code. Thanks in advance for your help.

  • After splitting a repo, new repos are many time larger
  • Get a list of all tags between two commits
  • Setting up a Git repository for a .NET solution
  • How to squash commits on Bitbucket after they have been pushed?
  • How can I list all branches that contain commits newer than a specific date?
  • Gitosis: setting repository config variables
  • Difference between “Force” and “Override branch if exists” in Tortoise Git
  • Git: Track permission change 777 to 444
  • git log --all to ignore disconnected parts of history graph
  • Updating project version number on git push
  • Errors cloning git project using Cygwin, msysgit Bash shell works
  • How to squash after checking out multiple branches in between?
  • 2 Solutions collect form web for “Git Checkout reverted code to older commit, how to revert back?”

    Check the git reflog and find your commit.

    Safest thing is to create a branch at the “lost” commit, then check if everything is dandy using gitk or git log -p

    git branch recovery HEAD@{1} # use whatever commit you need
    git log -p recovery
    

    This new branch can then be merged, rebased on top of master, commits of it cherry-picked, etc. There are many possibilities in git to shoot yourself in the foot but also several more ways to re-attach that foot (possibly to your arms).

    If you haven’t done any new commits on master, you can simply merge the commit in question, which will be resolved as a fast-forward merge by git:

    git merge HEAD@{1} # use whatever commit you need
    

    If you don’t care about any new commits on master and you simply want to reset master branch to that lost commit, use git reset. To not lose any changes, stash changes to your working copy first (git stash save)

    git reset --keep HEAD@{1}
    

    The next time you discover that you aren’t on any branch, use git branch newbranch or git checkout -b newbranch

    Use git reflog, get the sha of your new commit ( or you can reference it in format like HEAD@{1}) and use git cherry-pick, git merge etc to bring in the commit to master.

    Git Baby is a git and github fan, let's start git clone.