Git: Deleting Multiple Commits
Let’s say that you want to delete the last 3 commits that you’ve
already pushed to the remote repository. In this example, you want
566dab6
to be the new HEAD revision.
$ git log --pretty=oneline --abbrev-commit
57bc36b (HEAD -> master, origin/master, origin/HEAD) 3nd set of bad entries on 6th commit
dfb4bd3 2nd set of bad entries on 5th commit
0fd1e16 First set of bad entries on 4th commit
566dab6 Yet more good entries on third commit
d50370a More good entries on second commit
b5fbc6d Good entries on first commit
2cad4c7 Initial commit
You can use git reset
, git revert
, or
git checkout
to achieve this goal.
Using reset:
$ git reset --hard HEAD~3
$ git log --pretty=oneline --abbrev-commit
566dab6 (HEAD -> master) Yet more good entries on third commit
d50370a More good entries on second commit
b5fbc6d Good entries on first commit
2cad4c7 Initial commit
Then you have to force push to the origin:
$ git push --force
Using revert:
$ git revert --no-commit 57bc36b
$ git revert --no-commit dfb4bd3
$ git revert --no-commit 0fd1e16
or do all 3 at once:
$ git revert --no-commit HEAD~3..
Then do the commit:
$ git commit -m "Fixed commits"
$ git log --pretty=oneline --abbrev-commit
0da0f42 (HEAD -> master) Fixed commits
57bc36b 3nd set of bad entries on 6th commit
dfb4bd3 2nd set of bad entries on 5th commit
0fd1e16 First set of bad entries on 4th commit
566dab6 Yet more good entries on third commit
d50370a More good entries on second commit
b5fbc6d Good entries on first commit
2cad4c7 Initial commit
Using checkout:
Checkout that revision over the top of local files
$ git checkout -f 566dab6 -- .
$ git commit -a
$ git log --pretty=oneline --abbrev-commit
0da0f42 (HEAD -> master) Fixed commits
57bc36b 3nd set of bad entries on 6th commit
dfb4bd3 2nd set of bad entries on 5th commit
0fd1e16 First set of bad entries on 4th commit
566dab6 Yet more good entries on third commit
d50370a More good entries on second commit
b5fbc6d Good entries on first commit
2cad4c7 Initial commit
Tags: cli, git, source-control, motd