Undo the Last Commit

GitGitBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Git is a powerful version control system that allows developers to track changes made to their codebase. One of the most common tasks in Git is undoing a commit. This lab will teach you how to undo the last commit without rewriting history.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL git(("`Git`")) -.-> git/BasicOperationsGroup(["`Basic Operations`"]) git/BasicOperationsGroup -.-> git/commit("`Create Commit`") subgraph Lab Skills git/commit -.-> lab-12765{{"`Undo the Last Commit`"}} end

Undo the Last Commit

You have just committed changes to your Git repository, but you realize that you made a mistake. You want to undo the last commit without losing any of the changes you made. How can you do this?

For this lab, let's use the repository from https://github.com/labex-labs/git-playground. Follow these steps:

  1. Clone the repository, navigate to the directory and configure the identity:
git clone https://github.com/labex-labs/git-playground
cd git-playground
git config --global user.name "your-username"
git config --global user.email "your-email"
  1. Check the commit history:
git log
  1. Undo the last commit, creating a new commit with the inverse of the commit's changes:
git revert HEAD
  1. Check the commit history again:
git log

This is the result of running the git log --oneline command:

532b49b (HEAD -> master) Revert "Added file2.txt"
d22f46b (origin/master, origin/HEAD) Added file2.txt
cf80005 Added file1.txt
b00b937 Initial commit

Summary

Congratulations! You have successfully completed the lab to undo the last commit in Git. Remember that git revert HEAD is a powerful tool that allows you to undo changes without losing any of the work you have done. Keep practicing and exploring Git to become a Git expert.

Other Git Tutorials you may like