Removing a Commit with Interactive Rebase
For more complex history manipulation, such as removing a commit from the middle of a branch, you can use interactive rebase (git rebase -i). This is a very powerful command that rewrites commit history, so it should be used with caution, especially on branches that are shared with other developers.
Our goal is to remove the commit with the message "fix: Add a temporary file that should be removed". Looking at the current log, this commit is now HEAD~3.
Start the interactive rebase process:
git rebase -i HEAD~4
This command will open your text editor (vim by default) with a list of the last 4 commits.
pick fd5a181 fix: Add a temporary file that should be removed
pick 5f27a4d docs: Update documentation in file1
pick 284be6f chore: Add last-commit file again
pick 8a460c5 Revert "feat: Add file2.txt"
## Rebase 9403080..8a460c5 onto 9403080 (4 commands)
#
## Commands:
## p, pick <commit> = use commit
## d, drop <commit> = remove commit
## ...
To remove the commit, change the word pick to drop (or d) for the line containing "fix: Add a temporary file that should be removed".
Change this:
pick fd5a181 fix: Add a temporary file that should be removed
To this:
drop fd5a181 fix: Add a temporary file that should be removed
In vim, press i to enter insert mode, make your changes, then press Esc to exit insert mode. Save and exit by typing :wq and pressing Enter. Git will replay the remaining commits on top of the new history.
Check the log to see the result:
git log --oneline --graph
The "bad" commit is now gone from the history.
* a5b4c3d (HEAD -> master) chore: Add last-commit file again
* f9e8d7c docs: Update documentation in file1
* 1e2d3f4 Revert "feat: Add file2.txt"
* 5e1a3b2 feat: Add file2.txt
* 1b4c0a9 feat: Add file1.txt
Also, check the files in the directory. The file bad-commit-file.txt has been removed.
ls