How do I use 'git reset --hard HEAD' to revert to a previous commit?

 

You can use the git reset --hard HEAD command to reset your Git repository to the most recent commit (HEAD). If you want to revert to a specific previous commit, you should specify that commit's identifier (hash) instead of HEAD. Here's how you can do it with an example:

Let's assume you have the following commit history:

sql
* 0123456 (HEAD -> master) Merge branch 'feature' |\ | * abcdef1 Implement feature A |/ * 7890abc Fix bug B * 1234567 Add new feature C * 9876543 Initial commit

In this example, you want to revert to the commit with the hash 7890abc, which is "Fix bug B."

To revert to that commit using git reset --hard, follow these steps:

  1. Open your terminal or command prompt.

  2. Navigate to the Git repository where you want to perform the reset.

  3. Run the following command, replacing 7890abc with the hash of the commit you want to revert to:

bash
git reset --hard 7890abc

After running this command, your repository will be reset to the specified commit, discarding all changes made after that commit. Be cautious when using git reset --hard because it can lead to irreversible data loss.

In the example above, your commit history will look like this after the reset:

sql
* 7890abc (HEAD -> master) Fix bug B * 1234567 Add new feature C * 9876543 Initial commit

The HEAD pointer now points to the "Fix bug B" commit, and any commits made after that have been removed from your branch.

Comments