Using ‘git reset’ to revert to previous commit

A question that comes up with developers is how to use git reset– hard HEAD to revert to previous commit. Luckily there is an easy solution to follow to correct this.

First of all git reset —  hard is a very dangerous command because it eliminates all of your noncommitted changes. Be sure to always double check that the output of git status is empty (clean) before you begin using it.

Git records the state of the files when you stage them with git add or when you make a commit. When you have created a commit, which will have your project files stored in a particular state, they ae safe. But be sure to note that Git does not take track of changes to your files. For example, if you do git add to stage a newer version of the file, this will override the past staged version of the file in the staging area.

When you want to revert to a past commit using git reset – – hard, add <SOME-COMMIT>. Then Git will:

  1. Make your present branch (typically master) back to point at <SOME-COMMIT>.
  2. Then it will make the files in the working tree and the index (“staging area”) the same as the versions committed in <SOME-COMMIT>.

HEAD shows your current branch, or current commit, meaning that all git reset –hard HEAD will do is to throw away all of the uncommitted changes you have.

Here is another example, presume that the good commit that you want to go back to is f414f31. (You can find that via git log or by viewing any history browser.) You then have a few different choices dependent on what you would like to do:

  1. You could make your current branch to point to the older commit instead. This can be done with git reset –hard f414f31. Yet, this is rewriting the history of your branch, so if you share your branch with anyone it is best to not use this option. Also, the commits you did after f414f31 will no longer be included in the history of your master branch.
  2. You could also make a new commit that signifies exactly the same state of the venture as f414f31. This will keep the history the same, and it will not change the record of the branch’s history. You can do that using the steps these suggested steps:

git reset –hard f414f31
git reset –soft HEAD@{1}
git commit -m “Reverting to the state of the project at f414f31”

Want faster WordPress?

WordPress Speed Optimization

Try our AWS powered WordPress hosting for free and see the difference for yourself.

No Credit Card Required.

Whitelabel Web Hosting Portal Demo

Launching WordPress on AWS takes just one minute with Nestify.

Launching WooCommerce on AWS takes just one minute with Nestify.