Feedback

Chat Icon

Learn Git in a Day

Everything you need, nothing you don't

Oops - How to Undo Anything
29%

Undo a Commit Without Losing History

What if you've already committed something and you want to undo it? You could have pushed it to a shared repository, so you can't just delete the commit. Instead, Git lets you create a new commit that reverses the changes of a previous one. This is called a revert.

Let's say we decide the multiplication function was a mistake and we want to remove it. First, find the commit hash:

git log --oneline
c3d4e5f (HEAD -> main) Add multiplication function
b2c3d4e Add subtraction function
a1b2c3d Add calculator with addition function

To revert the most recent commit:

git revert HEAD --no-edit

The HEAD keyword refers to the most recent commit. The --no-edit flag tells Git to use the default revert message instead of opening a text editor. Git will create a new commit that undoes the changes from the multiplication commit.

Check the log:

git log --oneline

Output:

d4e5f6g (HEAD -> main) Revert "Add multiplication function"
c3d4e5f Add multiplication function
b2c3d4e Add subtraction function
a1b2c3d Add calculator with addition function

Notice that the original commit is still there - Git didn't erase history. It added a new commit on top that reverses the changes. If you look at calculator.py now, the multiplication function is gone:

python3 calculator.py

Learn Git in a Day

Everything you need, nothing you don't

Enroll now to unlock all content and receive all future updates for free.

Unlock now  $9.99$7.49

Hurry! This limited time offer ends in:

To redeem this offer, copy the coupon code below and apply it at checkout:

Learn More