How to clean the commit history in git 🔍

06/01/2025 06/01/2025 devops 2 mins read
Table Of Contents

To clean the commit history in Git, you can follow a series of steps that effectively remove all previous commits while keeping the current state of your code. This process is often used when the commit history contains unnecessary or sensitive information. Here’s how to do it:

Steps to Clean Git Commit History

  1. Create an Orphan Branch: This step creates a new branch without any previous commit history.

    Terminal window
    git checkout --orphan new_branch
  2. Add All Files: Stage all files in your working directory for the new commit.

    Terminal window
    git add -A
  3. Commit the Changes: Make a new initial commit with all the files.

    Terminal window
    git commit -m "Initial commit"
  4. Delete the Old Main Branch: Remove the old branch that contains the history. This action is irreversible.

    Terminal window
    git branch -D main
  5. Rename the New Branch: Rename your newly created branch to main (or your preferred name).

    Terminal window
    git branch -m main
  6. Force Push to Remote Repository: Update your remote repository to reflect these changes, effectively overwriting the history.

    Terminal window
    git push -f origin main

Important Considerations

  • Data Loss: This process permanently deletes all previous commits, so ensure you have backups if needed.
  • Collaboration Impact: If others are using the repository, communicate these changes as they will lose access to prior commit history.

This method is particularly useful for cleaning up repositories before public releases or when sensitive data has been committed unintentionally.