DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Cover image for Fix mistaken commits in Git ๐Ÿ”!
ArunKumar Nadikattu
ArunKumar Nadikattu

Posted on

Fix mistaken commits in Git ๐Ÿ”!

It is common issue that every developer makes code mistakes at any point of time in his career. One such mistake happens with git also.

Let assume that you've committed some code and later realised that
it is a false commit. Now you want to undo that bad commit. so, how do you do it ?

There are 2 possible ways to undo it: git reset and git revert.

git reset

git reset will move both HEAD ref pointer and current branch ref pointer to specified commit.

You should be careful when resetting as this will change the commit history.

It has 3 main options:

  1. --mixed: The Staging Index is reset to the state of the specified commit. Any changes that have been undone from the Staging Index are moved to the Working Directory. This is the default option.
  2. --hard: It will remove all unstaged changes. Most dangerous option.
  3. --soft: The uncommitted changes or the commits in-front of selected commit will not be removed. It is the most safest option.

command ยป git reset [ --soft | --mixed | --hard ] <commit-hash>

git revert

Unlike git reset, git revert does not move the ref pointers to that snapshot. This command will uncommit the targeted commit, and that commit can be anywhere in-between the git timeline. A revert command takes user specified commit, inverse the changes of that commit, and finally create a new commit. This newly created commit will be appended at top of the commit timeline.

command ยป git revert <commit-hash>

When to use reset & revert ?

revert doesn't modify commit history, unlike reset. With revert you can target any particular commit in history, whereas reset only works backword from last commit.

In conclusion, use revert if the changes also exist in remote repository and use reset if the changes exist locally.


Follow me on Twitter: twitter.com/mastrero_
Github: github.com/mastrero
LinkedIn: linkedin.com/in/arunkumar-nadikattu

PS: This is my first post in dev.to

Top comments (0)

We are hiring! Do you want to be our Senior Platform Engineer? We're hiring for a Senior Platform Engineer and would love for you to apply.

Head here to learn more about who we're looking for.