Want to change my master to an older commit, how can I do this?

Solution 1:

If you want to do this and revert the master to the previous commit:

git checkout master~1            # Checkout previous commit on master
git checkout -b new_master       # Create branch for new master
git branch -D master             # Delete old master
git branch -mv new_master master # Make new_master master

Alternatively:

git reset --hard master~1        # Reset current branch to one commit ago on master

Solution 2:

Your question is unclear. I think what you are asking for is this:

git push -f origin $old_commit_id:master

What will this do? It will push the $old_commit_id commit to origin as the new head of origin’s master branch.

If that is what you wanted, you do not need to touch your local master branch at all.

Solution 3:

If you want to avoid force pushing, here's how to revert your repo to an older commit and preserve all intervening work:

git checkout 307a5cd        # check out the commit that you want to reset to 
git checkout -b fixy        # create a branch named fixy to do the work
git merge -s ours master    # merge master's history without changing any files
git checkout master         # switch back to master
git merge fixy              # and merge in the fixed branch
git push                    # done, no need to force push!

Done! Replace 307a5cd with whatever commit you want in your repo.

(I know the first two lines can be combined, but I think that makes it less clear what's going on)

Here it is graphically:

c1 -- c2 -- c3 -- c4 -- c2' -- c5 ...
        \              /
         '------------'

You effectively remove c3 and c4 and set your project back to c2. However, c3 and c4 are still available in your project's history if you ever want to see them again.

Solution 4:

use git reset --hard <old commit number>

it will reset the HEAD to this old commit.

additionally, you need to use git push -f origin to alter the remote repo too.

Solution 5:

You can just git checkout <commit-id>, do whatever you need to do, then git checkout master to get back to the new code.

If you actually need to modify the old code to release it, then you should probably:

git checkout -b my_release <commit-id>
... prepare code for release ...
... release code ...
git checkout master
git merge my_release

Also, I can't recommend git flow enough. It makes all of this quite easy.