Before talking about ‘git reset –hard’ option of git reset command, let’s have a look on how you can undo the changes made by the commit or recent commit. We will provide you a detailed explanation here so that you can easily understand the whole process.
As a developer when you work with “Git” you need to make some changes like creating branches, adding files, and staging and committing them. But, sometimes the changes you have made are not good and you do not get the result you want. In need of desired results, you may want to undo them or revert the changes you just made. The technique of going back to the previous commit or undoing the previous changes is called “reset to Head”.
The fundamental structure for using the git reset command is:
git reset [<mode>] [<commit>]
There are three modes in which the command works:
- git reset –mixed
- git reset –soft
- git reset –hard
Lets understand all of the above modes of command briefly.
git reset –mixed
It’s a mode of reset that allows you to unstage changes that are currently in the staging area, moving those changes back into the working directory.
syntax:
git reset --mixed <commit-hash>
git reset –soft
This mode of reset allows you to move the HEAD pointer to a different commit without altering the staging area or the working directory.
syntax:
git reset --soft <commit-hash>
git reset –hard
It is a powerful Git command use to align the HEAD pointer, staging area, and working directory to match a specific commit. Here “–hard” stands for hard reset. This command is particularly useful when you want to discard all the changes made after a certain commit. It reverts the repository to a specific state in the commit history when it runs.
However, it’s important to use the command carefully because it permanently deletes any uncommitted changes in the working directory. Also It is impossible to recover the changes. Make sure you have a backup of the data before executing it because You will lose all local changes once the command has been executed.
Here ‘–hard’ is identified as reset mode, meaning it removes all changes in the working directory and index area, resetting them to match the specified commit.
Here’s how you can use it:
git reset --hard <commit-hash>
Or if you want to undo the changes made by the recent commit, then here’s how you can use it:
git reset --hard HEAD
Here HEAD is a reference to the latest commit on the current branch. It’s a symbolic name that always refers to the latest commit.