DEV Community

Cover image for How do I discard or undo changes in Git
KOTESWAR RAO MEESALA
KOTESWAR RAO MEESALA

Posted on

How do I discard or undo changes in Git

Undoing changes is a most common scenario when using Git and one that everyone comes across. There are ways to undo changes that are committed locally(reset) and undo changes that are published remotely(revert). I will cover commands used to undo things that are committed locally.

Alt Text

Git reset:

git reset is the command that one needs to use to reset the changes, whether those changes are in working directory, staging area or the ref HEAD points to. By default, HEAD always points to the latest snapshot in a particular branch. Git reset command comes with few options to move this HEAD to point to the commit you want.

git reset --soft HEAD~1

This tells git to move what the branch HEAD points to and stop there. No matter what form of reset with a commit you invoke, this is the first thing it will always try to do. It doesn't go further resetting staging area and working copy. Leave them as they were. Here, it moves the HEAD to its parent commit(one commit before it).

git reset --mixed HEAD~1

This is the default. This is same as git reset HEAD~1. Now, git proceeds to make changes to index and update its contents so that it looks like what HEAD points to. It means, it unstages everything and this is where the command will stop. It will not proceed to overwrite changes in working copy. Now, the HEAD, and the index are in sync.

git reset --hard HEAD~1

This resets everything. It moves the HEAD, updates index and rolls back changes to working directory. Now, all the players are in sync. You undid your last commit, the git add and git commit commands, and all the work you did in your working directory.

P.S Instead of passing a commit hashcode, one can pass a file path to reset.
Eg: git reset index.js
This unstages all the changes in that file. This is the output of the git status command that suggests you to run this to unstage a file.

That's it !! You can start using based on your use-case and be careful with git reset --hard as it will rmove the changes from working directory as well.

Top comments (1)

Collapse
 
captainawesomedi profile image
Di Wu

with new git version you could try git restore 😉