Remove file from all commits in git
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.
Subscribe to my newsletter
Read articles from Enow Sinke directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Enow Sinke
Enow Sinke
Hey there! I'm Sinke, and I'm all about that tech life, especially when it comes to fintech. Currently, I'm on a mission to become a bad-est Full Stack Software Developer, mastering both the front-end and back-end game. But you know what really gets me hyped? AI, baby! I can't get enough of it. I'm super passionate about exploring the endless possibilities it offers and making a mark in this exciting field. When I'm not geeking out over code, you can find me talking shop about Software Engineering and anything else that grabs my attention. I'm always up for a good conversation and love diving into new ideas. Oh, and here's a fun fact about me: I'm a huge fan of Choral Music. There's something magical about those harmonies and melodies that just speaks to my soul. It's my escape from the tech world and a reminder of the beauty of artistic expression. So, join me on this wild tech journey as I chase my dreams and create some serious magic in the world of technology. Let's make waves together!