DEV Community 👩‍💻👨‍💻

Cover image for Undoing Changes in git
vivek atwal
vivek atwal

Posted on

Undoing Changes in git

Undoing a Commit

Similar to unstaging, we occasionally may want to undo an entire commit. To clarify, when we say "undo a commit", we mean remove that commit from our history, and revert to the point at which the files were staged (with the changes captured in the commit).
The command used to undo a commit is:

git reset --soft HEAD^
Enter fullscreen mode Exit fullscreen mode

To break this down, HEAD refers to the current branch, and HEAD^ means one commit back, aka the "parent commit". The --soft here specifies that we should reset the branch (to point at that parent commit), but otherwise leave the files in the working directory and the index untouched.

This has the effect of undoing the commit, taking us back to just before we made it. Note that it leaves our changes staged in the index.

While useful, this is a complex command to remember, so once again we can create an alias, mapping this operation to the intuitive "uncommit" alias name.

git config --global alias.uncommit 'reset --soft HEAD^'
Enter fullscreen mode Exit fullscreen mode



 

Unstaging Files

Occasionally we'll find that after making a round of changes, we realize that some of the changes are entirely unrelated to others.
Perhaps we've run git add ., but we then realize that we only want to commit two of the three files that are now staged.
Once again, we can use a simple Git command to undo this.

git reset filename
Enter fullscreen mode Exit fullscreen mode



 

Checkout to Undo Changes

To remove a particular file changes from working directory

git checkout filename
Enter fullscreen mode Exit fullscreen mode

To remove all the changes from working directory

git checkout .
Enter fullscreen mode Exit fullscreen mode

NOTE This is one of the few dangerous operations in Git. If you run checkout without staging or committing your changes, Git will destroy your work and you will not be able to get it back. Be sure to use caution with git checkout .!

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.