Permanently revert GitHub branch to a specific commit

Please note that this is a very dangerous maneuver, especially when working with multiple collaborators. This should be avoided unless absolutely necessary. You will be essentially tampering with history, and making irreversible changes by following the steps below.

Step 1: Get the commit ID of the commit you wish to take your branch back to

This can be done with from github.com

or from the command line. Go to the folder/directory of the project of your interest, make sure you are on the correct branch (using git checkout <branch_name>), and then run git log (press q to quit the logs)

Step 2: Run the following command in the command line:

git reset --hard <commit_id>

In the example above, it will be

git reset --hard 360421f

You may be wondering the significance of the –hard qualifier. This StackOverflow answer does an excellent job of explaining it.

Step 3: Finally, force push this to the origin branch.

git push -f origin <branch_name>

For instance, if you are on the master branch,

git push -f origin master

That’s it. All commits AFTER 360421f (or whatever commit ID you selected) have been deleted. History has been re-written. I just hope you know what you just did.

The better way

Instead of deleting history from GitHub, what you can do instead is create a new branch from the specific commit of your interest, and start development on this new branch. This way, no data will be lost, and the old branch can soon be pushed into insignificance.

In order to create a new branch from a specific commit, you can run the following command:

git branch <branch-name> <commit-id>

For instance, in the above case, you could run the command:

git branch new-branch-demo 360421f

Now, publish this branch to GitHub using

git push origin <branch-name>

In the above example,

git push origin new-branch-demo

Found this post helpful? Then check out further posts on iotespresso.com. Also, follow IoT Espresso on Twitter to get notified about every new post.

Leave a comment

Your email address will not be published.