Dev Day 7: Reverting and Resetting in Git Bash

In the last article, we learned how to create additional branches, switch between the branches, and how to merge one branch’s commits to another branch. But what if we merged some commits to the Main branch and find that there is an issue, and we need to undo that commit? This again, is where utilizing a Version Control System is beneficial to our project.

First, we need to find a good restore point to go back to. We do this by looking at the commit log using the command git log.

Here we see all the commits that have been made within this branch. If we would like to revert to a previous commit, we can select and copy the hash code for that previous commit and, if needed, press q on our keyboard to exit the log. With the hash code copied we can then treat that commit just like a branch and preview the state of that commit to ensure that this is the point in time that we would like to revert the Main branch. To do this, we will use the command git checkout and paste the hash code.

With this commit state activated, we can preview to make sure that this is the correct point in time that we would like to revert our project. We can merge this commit state with a branch, we can create a new branch for this commit state, or we can simply ignore this commit state and go back to where we were. For best practice purposes, we will look at creating a new branch from this commit state.

To create a new branch from this commit state, use the command git checkout -b and add a new branch name (we will use the name test), and paste the hash code for this commit state as seen below.

Now the commit state is a new branch called Test and we can use it just like a normal branch and merge it with another branch once we are sure that is what we want to do. This is the safest route for reverting our project to a previous state.

Alternatively, if we did not want to use this commit state and look at a different state, we can run the git checkout command with a different hash code, or we can switch to a different branch if we choose not to revert at all.

The is also a way to reset the Main branch to a previous state using a commit hash code. Although this is not recommended due to data loss, we can reset our Main branch by activating the Main branch and using the command git reset — hard and paste the hash code for the point in time that we would like to rest the project.

Now the HEAD is at the new state and all commits that were made after this state are lost. Next, we need to push this new state back to the server using the command git push — force origin main, which will update the webserver and delete those same commits.

Again, resetting the Main branch, or any branch for that matter, comes with a great deal of risk with losing data. It is always a best practice to revert by branching out the commit states.