What are the reset, restore, and revert commands in Git?

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.

The git reset command

The 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:

  1. 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.

  1. To navigate back to the commit we do the following:

git reset <commit_hash>

The git restore command

The 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.c
git 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

The git revert command

The 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.

Conclusion

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.

Free Resources