How to remove Git commits from REMOTE

Albert Viilik
3 min readMar 5, 2020

You would like to remove one or more commits from the remote of a repository. I am sure you have significant reasons; therefore, I won’t waste your time explaining why you shouldn’t do it. I do warn you though, doing it this way is a bad developer practice.

For this demonstration I prepared a sample git repository and hosted it on GitHub. It contains a single file README.md which I changed through multiple commits so we have something to work with.

The repository looks like this:

Code View

And has the following commits:

Commits View

For the sake of this tutorial we will assume you want to remove last 5 commits.

The first step would be navigating to the cloned repository on your system.

I have mine stored under “/Users/user_name/git/GitHub/sample_repository” therefore I will navigate to it by executing the following in the Terminal:

$ cd /Users/user_name/git/GitHub/sample_repository

To get rid of the unwanted commits we will use Git rebase. To start an interactive rebase session execute this command.

$ git rebase -i HEAD~5

This will open an interactive rebase session in which you will be able to decide what to do with commits. Git rebase gives you the power to modify your history, and interactive rebasing allows you to do so without leaving a “messy” trail. This creates the freedom to make and correct errors and refine your work, while still maintaining a clean, linear project history.

The rebase session will open in your default editor. Mine is Atom.

It will look like this if you are using Atom as your default editor.

Next, you need to change “pick” to “d” or “drop” for each commit that you would like to get rid of. We will do this for all commits as we want to get rid of our last 5 commits in this tutorial.

Now, after you made the changes the file should look like this:

When you are finished selecting the commits for removal, save the file. I will do so by pressing Command + S. (Ctrl + S on Windows/Linux). After saving we can close rebase session.

As a last step, to push these changes to the remote, we will run the following command in the Terminal:

$ git push --force

Now, the repository on GitHub looks like this:

Code View

The unwanted commits have disappeared from the commit history, and the file Readme looks the way it did after the commit “Change 2”.

--

--

Albert Viilik
Albert Viilik

No responses yet