Revert to a previous Git commit

Sometimes I see developing software in Git as more of universal undo, but for that to work its important to know how to fix things when they go wrong.

Revert to a previous Git commit

I make heavy use of git for all my software development, when asked what the point is for a one man development team to something as powerful as git I always reply "universal undo".

With a recent update to the site i finally got the chance to use it the way I'd always expected to, and it worked exactly as expected but the correct process was harder to find than expected. So here is how I was able to revert my master git branch after committing some bad code:

Reverting Working Copy to Most Recent Commit

To revert all uncommitted changes back to the previous commit: git reset --hard HEAD where HEAD is the last commit in your current branch

Reverting Working Copy to an Older Commit

This is a some what controversial step, but it was what I needed and the only thing I could find that would work. The better option is to avoid a hard reset if other people have copies of the old commits, because using a hard reset like this will force them to have to resynchronize their work with the newly reset branch. This isn't a problem for me, but it is worth mentioning encase it would be for you.

To revert back to an already committed change:

    # Resets index to former commit; replace 'ad957a69' with your commit code
    git reset ad957a69

    # Moves pointer back to previous HEAD
    git reset --soft HEAD@{1}
    git commit -m "Revert to ad957a69"

    # Updates working copy to reflect the new commit
    git reset --hard