Skip to main content

Undoing Commits

Git is a powerful tool that helps us manage, track, and control our code changes. One of the most common situations you may find yourself in is making a commit and then realizing that you need to undo it. In this tutorial, we will explore different ways to undo commits in Git.

Understanding Git Commit

A commit in Git is like a snapshot of your project at a particular point in time. Whenever you make a commit, Git saves a reference to that snapshot so you can revert or go back to that state whenever you want.

How to Undo Commits in Git

There are various ways to undo commits in Git. We will learn about three of them: git reset, git revert, and git commit --amend.

Using git reset

The git reset command is a powerful tool that allows you to move the HEAD pointer to a specified commit. Let's look at an example:

git reset --soft HEAD~1

In the above command, HEAD~1 means the commit before the current one. The --soft option doesn't touch the index file or the working tree. It only moves the HEAD pointer.

Remember, git reset is a powerful command and can be destructive if not used carefully.

Using git revert

While git reset is a destructive command, git revert is a safe command. It creates a new commit that undoes the changes made in the previous commit.

Here is an example of how to use git revert:

git revert HEAD

In this command, HEAD is the pointer to the current commit. So, git revert HEAD will create a new commit that undoes the changes made in the last commit.

Using git commit --amend

If you made a mistake in your last commit and you want to fix it, git commit --amend is your best friend.

Here is an example of how to use git commit --amend:

git commit --amend -m "New Commit Message"

This command replaces the last commit with a new one. The new commit will have the same parent as the old one.

Conclusion

In this tutorial, we learned how to undo commits in Git using git reset, git revert, and git commit --amend. Remember, git reset is a destructive command and should be used carefully. On the other hand, git revert and git commit --amend are safe commands. They create new commits instead of destroying old ones.

Learning how to undo commits is a crucial skill in Git. It allows you to easily fix mistakes and maintain a clean and understandable project history.

In the next section, we will learn about branching and merging in Git. Stay tuned!