Remove file from all commits in git

Remove file from all commits in git

Working with Git

Locally

If you realized you added an unnecessary file to a commit and you have not yet pushed this commit…

  1. It is best practice to do this on a temporary branch

    git checkout -b file-remove

  2. Say the file you want to remove is called Sample.class

    git filter-branch --tree-filter 'rm -f Sample.class'-- --all

  3. Update the repo to have the changes

    git push origin file-remove --force

  4. Cleanup

    git checkout main

    git branch -D file-remove

Remotely

If you realized you had already pushed the commit with the unnecessary file(s)...

Note: Discuss this with team members first, as you will be rewriting the commit history, which may cause some issues.

  1. Delete the files locally

    git rm Sample.class

    git commit -S -m “fix(files): removed unnecessary files”

  2. Push to your branch

    git push -u origin <branch_name>

  3. Rewrite remote history and remove the files from all commits

    git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch Sample.class' --prune-empty -- --all

In my case, I have multiple unnecessary files and a directory.

git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch playWithJava/calculator/Calculator.class playWithJava/calculator/Main.class playWithJava/sum/*' --prune-empty -- --all

Basically, any commit with the unnecessary files or directories will be deleted.

Note: Before I ran this command, I had 11 commits. After I ran the command, I had 6 commits. This is why you should consult with team members before rewriting commits.

git push origin --force --all

I first published this here.