Explain how reset command works in Git

GitGitHubOpen SourceSoftware & Coding

The commit command moves the HEAD of a branch implicitly. The below diagram shows that initially HEAD was pointing to commit c1. After each commit operation the HEAD pointer moves ahead to the new commit. We can perform a reset using the HEAD pointer or commit hash.


The git reset command will explicitly or forcibly move the HEAD of the branch to a specific commit.

When resetting the HEAD pointer, we have 3 options −

  • Soft
  • Mixed
  • Hard

Hard Reset

When performing a hard reset, git will copy the commit snapshot into the working area as well as the staging area. Due to this any changes done in the current working directory or staging area prior to performing the hard reset will be lost. The syntax to perform a hard reset using the HEAD pointer will be-

git reset --hard HEAD~<i>

where, i is the number of commits to move backwards

For example, the following command will move the HEAD 2 commits backwards.

git reset --hard HEAD~2

The following diagram shows the position of the HEAD pointer after executing the above command.

Since the commit is now pointing at c1, the other commits c2 and C3 will be garbage collected.

Mixed Reset

This is the default option for resetting. Mixed reset copies the snapshot from the repository to the staging area only. So, the current changes in the working area will stay intact.

The syntax to perform a hard reset using the HEAD pointer will be −

git reset --mixed HEAD~<i>

where, i is the number of commits to move backwards

For example, the following command will move the HEAD 2 commits backwards.

git reset --mixed HEAD~2

In our example, the position of the HEAD pointer upon a mixed reset will be as shown in the below diagram.

Soft Reset

When we perform a soft reset the commit snapshot is not copied to the staging area or to the working area. It will just move the HEAD explicitly to the commit. All changes in the working area and staging area will stay intact.

The syntax to perform a hard reset using the HEAD pointer will be −

git reset --soft HEAD~<i>

Where, i is the number of commits to move backwards

For example, the following command will move the HEAD 2 commits backwards

git reset --soft HEAD~2

In our example, the position of the HEAD pointer upon a mixed reset will be as shown in the below diagram −

raja
Published on 28-Apr-2021 14:10:11
Advertisements