Accidentally committing the wrong files to Git is a common mistake, but fortunately, it's easy to undo those commits from the local repository. In this tutorial, we'll explore four different ways to undo a commit in Git, including resetting, reverting, amending, and rewriting history.
Resetting is the easiest way to undo your last commit while leaving your working tree untouched. To reset your last commit, use the following command:
$ git reset HEAD~
This command moves the HEAD pointer back one commit, but it leaves your files as they were. You can make corrections to working tree files and add them again before committing.
If you don't care about keeping the changes you made, use the following command instead:
$ git reset --hard HEAD^
This command moves the HEAD pointer back one commit and discards any changes you made after that commit.
If you have already pushed your commits to a remote repository, you should use the revert command. Revert creates a new commit that undoes the changes made by a previous commit.
To revert your last commit, use the following command:
$ git revert HEAD
This command creates a new commit that undoes the changes made by the last commit. You can edit the commit message if you want to.
If you just need to change the last commit, you can use the amend command. Amending allows you to modify the previous commit, including its commit message.
To amend the last commit, use the following command:
$ git commit --amend
This command will open the default text editor with the previous commit message. You can change the message or modify the index as needed.
If you need to rewrite history, you can use the git push command with the --force or --force-with-lease option. However, rewriting history can cause problems, especially if you have collaborators who have already pulled the changes you're trying to undo.
To rewrite history, use the following command:
$ git push origin your-branch-name --force-with-lease
This command overwrites the history of the remote branch with your local changes. However, you should only use this command if you know what you're doing.
Undoing a commit is a little scary if you don't know how it works. But it's actually amazingly easy if you do understand. In this tutorial, we've explored four different ways to undo a commit in Git, including resetting, reverting, amending, and rewriting history. Choose the method that works best for your situation and use it to undo your last commit.