How to Push a Previous Commit Back to the Top of the Master Branch in GitHub

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Having trouble trying to push an old commit back to the top of your master branch in GitHub? This can be quite the doozy! I find myself frequently wanting to return my GitHub repository back to a previous state, and Git does not make this easy to do! What usually happens for me is that whenever I’m ready to finally push the previous commit back to the master branch, I end up running into a merge conflict. Ouch.

So, this is what you need to do if you find yourself in this situation. First, checkout the old commit that you want to restore your repository to (replace ‘c0mm1t1d’ with the commit id you want to checkout):

$ git checkout c0mm1t1d

Then create a new branch to work with:

$ git switch -c my-new-branch

$ git push origin my-new-branch

For good measure, make a small change to your new branch and commit the change. I suggest adding a comment or some other superficial change so you can verify that your repo has been updated exactly the way you like. Then commit the change:

$ git add -A

$ git commit -m "bug fix"

$ git push origin my-new-branch

Now time for the magic! We will merge our new branch back into the master branch using the “favor ours merge strategy” to ensure that our new branch is favored over the old branch should any merge conflicts arise:

$ git merge -s ours master

$ git checkout master

$ git merge my-new-branch

$ git push origin master

Alight, so there’s one last key piece of information I must mention: At some point you are going to be prompted to “Please enter a commit message to explain why this merge is necessary”, and then will get stuck inside of some awful vi/vim editor which you can’t get out of. Here’s what you need to do! Enter a short message explaining the merge, press ESCAPE, type:

:wq
Then press ENTER again to exit the prompt. And that’s it! Your repo and master branch are back in business.

 

topherPedersen