How to Undo the Last Commit: Step-by-Step Guide

Ever hit "commit" only to realize you’ve made a mistake?

Don’t worry, we’ve all been there.

In this guide, let's check out exactly how to undo that last commit, whether it's correcting a typo or pulling back a bad code change.

It’s a quick fix that’ll keep your Git history clean without losing any work.

How to Undo the Last Commit

Steps to follow:

Undoing a commit in Git can be a powerful tool for maintaining a clean and organized project history.

1. Review the changes you've made in 'Source Control'.

2. There are two scenarios:

Scenario 1: Undo the Last Commit (before pushing). [Refer to step 3]

Scenario 2: Undo a Pushed Commit (revert). [Refer to step 8]

3. Use the 'git status' command to display the current state of the working directory and staging area in your Git repository.

4. Use 'git add .' command to stage all the changes in your working directory for the next commit.

5. Use 'git commit -m <commit-message>' to save your staged changes to the local repository.

6. Use 'git commit --amend -m "New commit message"' to modify the last commit message.

7. If you want to undo the commit without keeping the changes, use: 'git reset --soft HEAD~1'

Note: This moves the changes back to the staging area.

8. Use 'git status' command to display the state of the working directory and the staging area in a Git repository.

9. Use 'git add .' command to stage all the changes in your working directory for the next commit.

10. Use 'git commit -m <commit-message>' to save your staged changes to the local repository.

11. Push changes into your branch.

12. Use 'git revert' with the commit hash to create a new commit that undoes the changes.

Note: Copy the commit hash from your last commit message.

13. Use 'git revert <commit-hash>' to revert last commit.

14. Make the required changes and commit your code.

15. Finally push your updated code to your branch.

That's All! We have successfully reverted our changes.

Conclusion

Undoing the last commit doesn’t have to be a stressful experience.

With the simple steps covered here, you can make sure any errors are quickly corrected while keeping your project on track.

Keep practicing this approach to stay in control of your commits and maintain a spotless Git history!

Still have questions?

Send an email to archana@leadwalnut.com, OR

Book a FREE consultation with an expert developer here.