Search code examples
gitgithubopen-source

Delete files from pushed code on github


I have committed and pushed my changes to my forked copy of a project. Also I have raised a pull request to the repository from which I initially forked the project. Now I have to delete a file which I committed. How should I do it?


Solution

  • If the file only exists in the last commit, you can simply delete it, amend your commit and use git push --force to rewrite the commit on github:

    git rm file-to-delete
    
    git commit --amend
    
    git push --force
    

    If you want to delete the file from several previous commits, take a look at the github guide on this subject.

    In particular, you can use the BFG cleaner to delete files from a repo including all commits history:

    bfg --delete-files file-to-be-deleted
    

    Another alternative which doesn't require installing anything on top of git is the git filter-branch command:

    git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch file-to-be-deleted' --prune-empty --tag-name-filter cat -- --all
    

    After the changes are made locally, you must use git push --force to push them to github.

    In any case, you should add the file to your .gitignore so you don't accidentally commit it again in the future.