How to delete all commits in a Git repository and replace it with a single “initial commit”

If you have an existing Git repository with multiple commits (history) in it, and you would like to replace all the history with just a single commit, here’s how to do it:

NOTE: only do this if you know what you’re doing. Rewriting history in Git is usually considered a bad-practice, especially if you are collaborating with other people.

1. Create a copy of your existing repository on the filesystem

Firstly, create a copy of your existing directory that contains your Git repository. For example, if your Git directory is in /home/source, then create a copy of the folder and name it /home/source_clean.

cp -R /home/source /home/source_clean

2. Delete .git folder and reinitialize a clean git repository

Next you want to go inside the new copied folder, delete the local .git folder, and then re-initialize git so you get a clean repository.

cd /home/source_clean
rm -rf .git
git init

If successful, you should get the following output:

user@Ubuntu:/home/source_clean$ git init
Initialized empty Git repository in /home/source_clean/.git/

3. Create a new initial commit

Now that we have a clean Git repository with all of our files, we need to create a new commit. We do this by staging all current files and then committing.

Note: depending on your Git configuration the default branch will be named “master”. If the remote branch that you want to overwrite has a different name (Github uses “main”), make sure to switch to this branch (via “git branch -m “main”) before creating the initial commit.

git add -A
git commit -m "Initial commit"

4. Force push new master branch to remote/origin

Now we will force push the new (master) branch to our existing remote. Since our local branch only has 1 initial commit, when you do a normal push the remote Git server will normally reject this, since the history doesn’t match up. If you issue a “force push”, you ignore any errors and forcefully overwrite the target.

git remote add origin https://github.com/<your-username>/<your-repo>.git
git push -f origin

This should give you the following output:

user@Ubuntu:/home/source_clean$ git push origin main -f
Username for 'https://github.com': 
Password for 'https://<your-username>@github.com': 
Total 0 (delta 0), reused 0 (delta 0)
To https://github.com/<your-username>/<your-repo>.git
 + 8826953...b713a41 main -> main (forced update)

Now your Git repository is overwritten at the remote and will only contain your single “initial commit”. Success!

Published
Categorized as Git

By Leendert de Borst

Freelance software architect with 10+ years of experience. Expert in translating complex technical problems into creative & simple solutions.

Leave a comment

Your email address will not be published. Required fields are marked *