How to Delete Your Commit History in Git

Maybe you want to publish a project but don’t want everyone to see what mess you created before your initial release. Maybe you want to hand over a Git repository to a third party who should not peek into your complete git commit history. Whatever the reason, here is how you can get rid of all past commits in a branch without losing your latest work.

Disclaimer: what follows are a few Git commands for the terminal. If you are a little bit like me, you probably prefer a GUI like Git Tower (❤️). But in this case, using the command line seems to be the fastest solution. Also, make sure to install Git on your machine. And probably don’t do this in an established repo that you share with a larger team as it might break stuff for them.

First, make sure you are in a your project root directory and checkout a new branch with the --orphan flag.

git checkout --orphan latest_branch

This will create a new, empty (“orphaned”) branch without any commits. Then, add all the files in your working directory:

git add -A

Now commit all your changes.

git commit -am "first commit message"

With all your work safely stored in the new branch, it is time to delete the old branch, e.g. the main branch:

git branch -D main

Now – and you probably already guessed it, right? – rename the current branch (the one you just created) into main:

git branch -m main

And finally, update the remote repository using the force of Git. Thanks to Frederic Hemberger for pointing out that --force-with-lease is probably better than using --force because it won’t overwrite the commits of others in case the branch has changed in the meantime.

git push --force-with-lease origin main


I know all this might sound obvious to some of you and yes, I found this solution on StackOverflow, but I wanted to write it down to have it at hand the next time I need it. And maybe it is useful for you as well?

BTW, do you know what’s also useful when working with Git in the command line? Oh Shit, Git!


9 Webmentions

Photo of Frederic
Maybe add a note that you should never ever do this on an established repo when working with others (this might break stuff for them). Also --force-with-lease instead of --force is your friend (don't rewrite history if someone else committed in the meantime).