Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Old Commit from source code

From what I understand, each git commit stores the changes made to the tracked files since the last commit. Is there a way for you to just delete an old commit out of the source code? For example, if you had a text file

textfile.txt

Text line one
More text line

and you went ahead and committed git commit -m "Initial Commit"

You then edit textfile.txt again

textfile.txt

Text line one
More text line
Even more lines
Just one more line

and you went ahead and committed git commit -m "Added new lines 2"

You then made on final edit

textfile.txt

Text line one
More text line
Even more lines
Just one more line
These are the last lines
In this file

and commited git commit -m "Added new lines 3"

Is there a way to delete all changes in commit number 2 ("Added new lines 2") so that the file would look like:

textfile.txt

Text line one
More text line
These are the last lines
In this file

(Notice the removed lines Even more lines and Just one more line which were changed made in Commit 2)

like image 502
CoreCode Avatar asked Jun 10 '26 10:06

CoreCode


2 Answers

You can do this with rebase (you don't need an interactive rebase for this):

git rebase HEAD --onto HEAD~2

Which basically means:

Take all commits from HEAD and further (thus one commit), and apply them onto the parent of the parent (your first commit). So the parent commit (your second commit) is thus skipped.

Before:

     HEAD
      |
A--B--C

After:

A--B--C
 \
  C'
  |
 HEAD

Your HEAD now points to C' (A copy of the original C), but C' has now A as parent instead of B.

Edit:

From your comment on Klas Mellbourn's answer, it seems you want to keep the commit, but want to undo it's changes. That's what git revert does.

git revert HEAD~1
like image 146
Ikke Avatar answered Jun 12 '26 22:06

Ikke


The other answers (By KlasMellbourn and Ikke) erase the commit, "it never happened". Rewriting history like that isn't nice (but sometimes necessary...). You can use git revert (just issue it with --help for details) to create a new commit undoing the old one.

like image 23
vonbrand Avatar answered Jun 13 '26 00:06

vonbrand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!