Git: How to Undo a Commit

Updated: January 28, 2024 By: Guest Contributor Post a comment

Introduction

Git is a powerful tool for version control that allows developers to track changes, collaborate on projects, and revert code to previous states. Knowing how to undo a commit in Git is an essential skill that can save a developer from potential pitfalls. This tutorial will walk you through the steps to revert changes after you have committed them.

Understanding Git Commits

Before proceeding to undo a commit, it’s important to understand what a Git commit is. A commit is a snapshot of your repository at a specific point in time. When you make a commit, Git takes a snapshot of the files as they are and stores a reference to that snapshot. You can return to this snapshot at any time.

The Basic Undo: git reset

To undo the most recent commit, you can use the git reset command. There are a few variations of this command depending on how much of the commit you want to undo:

git reset HEAD~1

The above command will undo the last commit but keep the changes in your working directory. Your files will remain as they were just before you made the commit, allowing you to edit them further and re-commit if needed.

Undoing a Commit and Keeping Changes

If you want to undo the commit but also keep the changes staged (ready to be committed), you can use the --soft option:

git reset --soft HEAD~1

This command will move the HEAD pointer back one commit, but leave your files staged. You can then correct any issues and commit the changes again.

Undoing a Commit Completely

If you want to undo the changes completely, making your working directory match the repository before the commit, use the --hard option:

git reset --hard HEAD~1

Warning: This command will discard all changes in the working directory and staged files. Use with caution.

Undoing Multiple Commits

If you need to undo more than the last commit, you can specify how many commits to undo:

git reset --hard HEAD~2

This will undo the last two commits. Replace ‘2’ with the number of commits you wish to undo.

Using git revert for Public Commits

When working with a shared repository, using git reset is not advised because it rewrites history, which can cause issues for other collaborators. In this case, you’d use git revert:

git revert HEAD

This command creates a new commit that reverses the changes made by the last commit. It’s safe to use in public repos because it doesn’t alter the existing commit history.

To revert a specific commit, you can pass the commit hash like so:

git revert 1a2b3c4

Replace ‘1a2b3c4’ with the hash of the commit you want to revert.

Conclusion

Knowing how to undo a commit in Git allows you to maintain a clean and orderly code history. Always ensure that you understand the implications of the command you are using, and when in doubt, use methods that do not alter shared history.