Locally
If you realized you added an unnecessary file to a commit and you have not yet pushed this commit…
It is best practice to do this on a temporary branch
git checkout -b file-remove
Say the file you want to remove is called Sample.class
git filter-branch --tree-filter 'rm -f Sample.class'-- --all
Update the repo to have the changes
git push origin file-remove --force
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.
Delete the files locally
git rm Sample.class
git commit -S -m “fix(files): removed unnecessary files”
Push to your branch
git push -u origin <branch_name>
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.