How to remove file from Git history?

2020-02-07 16:06发布

Some time ago I added info(files) that must be private. Removing from the project is not problem, but I also need to remove it from git history.

I use Git and Github (private account).


On this thread Shows something similar but here is an old file that was added to a feature branch, that branch merged to a development branch and finally merged to master, since this, a lot of changes was done. So it's not the same and what is needed is to change the history, and hide that files for privacy.

标签: git github
5条回答
Rolldiameter
2楼-- · 2020-02-07 16:59

I have found this answer and it helped:

git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch path_to_file" HEAD

Found it here https://myopswork.com/how-remove-files-completely-from-git-repository-history-47ed3e0c4c35

查看更多
霸刀☆藐视天下
3楼-- · 2020-02-07 17:00

I used this GitHub article to use this, which led me to this command (similar to the accepted answer, but more robust):

git filter-branch --force --index-filter "git rm --cached --ignore-unmatch PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA" --prune-empty --tag-name-filter cat -- --all
查看更多
forever°为你锁心
4楼-- · 2020-02-07 17:02

Using the bfg repo-cleaner package is another viable alternative to git-filter-branch. Apparently, it is also faster...

查看更多
聊天终结者
5楼-- · 2020-02-07 17:04

If you have recently committed that file, or if that file has changed in one or two commits, then I'd suggest you use rebase and cherrypick to remove that particular commit.

Otherwise, you'd have to rewrite the entire history.

git filter-branch --tree-filter 'rm -f <path_to_file>' HEAD

When you are satisfied with the changes and have duly ensured that everything seems fine, you need to update all remote branches -

git push origin --force --all

Note:- It's a complex operation, and you must be aware of what you are doing. First try doing it on a demo repository to see how it works. You also need to let other developers know about it, such that they don't make any change in the mean time.

查看更多
够拽才男人
6楼-- · 2020-02-07 17:05
  • remove the file and rewrite history from the commit you done with the removed file(this will create new commit hash from the file you commited):

    git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA' --prune-empty --tag-name-filter cat -- --all

  • now force push the repo:

    git push origin --force --all

  • now tell your collaborators to rebase.

查看更多
登录 后发表回答