The Git reset, restore, and revert are popular commands used to manipulate changes in our Git repositories. They have similar functions and can be confused with each other.
git reset
commandThe git reset
command is used to move the state of a repository back to a previous commit. It discards the changes made after that particular commit. To use the git reset
command, we do the following:
Specify the commit we want to return to. To do this, use the git log
command. Entering this command would, by default, output a long list. To get a shorter list, add the --oneline
option. It displays the following:
The first seven characters of the commit hash
The commit message
The commit hash is typed along with the git reset
command. It tells the computer the commit we want to return to.
To navigate back to the commit we do the following:
git reset <commit_hash>
git restore
commandThe git restore
command is used to restore the last committed change and remove the uncommitted local changes made after it. This is the default operation performed by the git restore
command.
git restore <filename>
It can also be used with wildcards as seen in the second line of the code below.
git restore multiply.cgit restore *.c
It is also used to unstage
the changes added to the Staging area. In other words, it is used to undo the effect of git add
. It only unstages
the changes. It does not undo the changes made.
It does this with the --staged
option.
git restore - -staged <filename>
The following is an example of the command above:
git restore --staged calculator.c
git revert
commandThe git revert
command is also used to undo changes made to a repository. However, it does not remove these changes from Git history. It inverts the changes made after the specified commit. Then, it creates a new commit with the resulting changes.
The git revert
command requires that a commit ref/hash be passed along with it. As such, we need to specify the preferred commit to be reverted.
git revert HEAD
The git revert
command is particularly useful and safer because it prevents the loss of history.
As mentioned earlier, the Git reset, restore, and revert commands are similar. Hence, it is good to be cautious about which command is being used and whether or not it corresponds to the required result.