-
Open Terminal: Open the terminal and navigate to your Git repository directory using the
cdcommand. -
View Commit History: Before using the
git reset --hardcommand, check the commit history to determine which commit to revert to. This can be done with thegit logcommand, which displays a list of commits, each with a unique commit hash. -
Select the Commit to Revert To: Find the hash of the specific commit you want to restore to. For example, if the commit hash is
a1b2c3d, use this hash to revert. -
Execute the
git reset --hardCommand: Now, use the following command to reset HEAD and the current working directory to the commit you selected:
shellgit reset --hard a1b2c3d
Replace a1b2c3d with the actual commit hash you want to revert to.
- Check Status: After executing the
git reset --hardcommand, use thegit statuscommand to confirm the current working directory and index status. Your local working directory should now be restored to the historical commit you selected.
Note: git reset --hard is a destructive operation because it discards all uncommitted changes in the current working directory, including those in the staging area and the working directory. Therefore, before using this command, ensure that you no longer need these uncommitted changes.
Example:
Suppose I introduced a new feature in my project, but discovered that this feature actually broke other parts of the application. I decided to abandon the changes for this feature and revert to the state before I started it. I executed the git log command to find the commit hash before the feature implementation, assuming it is 9fceb02. Then I executed the command:
shellgit reset --hard 9fceb02
This will revert my codebase to the state before the feature implementation and discard all changes made after that. After this, I can use git status to confirm the changes and continue working from an earlier point.