How to remove a specific commit from the history
You want to remove a specific commit from the history. You can do this with git rebase -i.
Let’s say you have a git repository with the following commits:
alina
alina git:( main ) git log
commit ddad9c09b0edfec503b10bdaa17a204f6a4d571f (HEAD -> main)
Author: alina <alina@email.com>
Date: Wed Jul 12 08:11:35 2023 -0700
add A3.txt
commit bc67b5dddf274b3fd82c2641fddae670a8896cd2
Author: alina <alina@email.com>
Date: Wed Jul 12 08:11:31 2023 -0700
add A2.1.txt
commit 4400508c3c99389767a545d457b9517e2dd38de9
Author: alina <alina@email.com>
Date: Wed Jul 12 08:11:28 2023 -0700
add A2.txt
commit 98fcabe2f74e908a6b5e637bab456038f7cc591f
Author: alina <alina@email.com>
Date: Wed Jul 12 08:11:25 2023 -0700
:
alina git:( main ) █
and that corresponds to these files in your directory:
alina
alina git:( main ) ls
A1.txt A2.1.txt A2.txt A3.txt README.md
alina git:( main ) █
Now, you want to remove the commit add A2.1.txt
from the history.
To do this, you can make use of the command git rebase -i
, which takes the last commit you want to retain.
In this case, the commit we want to delete is bc67b5
, so the last commit we want to keep is its parent: 4400508
.
alina
alina git:( main ) git rebase -i 4400508c3c99389767a545d457b9517e2dd38de9
alina git:( main ) █
Running this command will open your editor with the necessary instructions.
The top part of the file contains the list of commits:
pick bc67b5d add A2.1.txt
pick ddad9c0 add A3.txt
Your goal is to remove the commit bc67b5d
. Simply delete that specific line from the editor, so that you only keep the desired commits.
pick ddad9c0 add A3.txt
Once you save and exit the editor, the rebase operation will be executed and the commit bc67b5d
will be removed from the history.
Upon confirmation, you will notice that the associated file has disappeared from your working directory.
alina
alina git:( main ) ls
A1.txt A2.txt A3.txt README.md
alina git:( main ) █
Additionally, the commit will no longer be visible in the log.
alina
alina git:( main ) git log
commit 3d51b5211ad852956918fc7a1e4ae4ea93ffc6d5 (HEAD -> main)
Author: alina <alina@email.com>
Date: Wed Jul 12 08:11:35 2023 -0700
add A3.txt
commit 4400508c3c99389767a545d457b9517e2dd38de9
Author: alina <alina@email.com>
Date: Wed Jul 12 08:11:28 2023 -0700
add A2.txt
commit 98fcabe2f74e908a6b5e637bab456038f7cc591f
Author: alina <alina@email.com>
Date: Wed Jul 12 08:11:25 2023 -0700
add A1.txt
commit 23c232cb2b121c7b86788cf1224ff6538d626a07 (origin/main, origin/HEAD)
Author: gitpowerup <gitpowerup@mail.com>
Date: Wed Jul 12 08:11:06 2023 -0700
:
alina git:( main ) █