Remove Git Commit from History

1 minute read

Occasionally, you may want to remove a commit from github/gitlab, for example, I pushed a commit to switched the jekyll theme from minima to minimal mistakes, and caused the gitlab pipeline failed when executing bundle install:

You must use Bundler 2 or greater with this lockfile.

I updated Gemfile.lock and thought it should fix the issue, but actually, it didn’t. I need to remove that commit, because the commit message says the issue was fixed, or it will make me confused sometime later.

There is an answer from stackoverflow user Can Berk Güder:

git reset --soft HEAD^
git push origin +master --force

Another way to remove the commit is using git rebase -i, for example, the bad commit you want to remove is the last commit, you can do git rebase -i HEAD~2 and delete the second line within the editor window that pops up.

You may fail to push to the remote if the branch is protected:

git push origin +master --force
Total 0 (delta 0), reused 0 (delta 0)
remote: GitLab: You are not allowed to force push code to a protected branch on this project.
To gitlab.com:fudongbai/fudongbai.gitlab.io.git
 ! [remote rejected] HEAD -> master (pre-receive hook declined)
error: failed to push some refs to 'git@gitlab.com:fudongbai/fudongbai.gitlab.io.git'

To fix this, go to project: Settings » Repository, click Exapnd on Protected Branches: protected branches