git删除历史 Git如何永久删除文件(包括历史记录)

Git如何永久删除文件(包括历史记录)

 

有些时候不当心上传了一些敏感文件(例如密码), 或者不想上传的文件(没及时或忘了加到.gitignore里的),html

并且上传的文件又特别大的时候, 这将致使别人clone你的代码或下载zip包的时候也必须更新或下载这些无用的文件,git

所以, 咱们须要一个方法, 永久的删除这些文件(包括该文件的历史记录).github

首先, 能够参考 github 的帮助:bash

https://help.github.com/articles/remove-sensitive-datapost

步骤一: 从你的资料库中清除文件

以Windows下为例(Linux相似), 打开项目的Git Bash,使用命令: 
url

git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch path-to-your-remove-file' --prune-empty --tag-name-filter cat -- --all

其中, path-to-your-remove-file 就是你要删除的文件的相对路径(相对于git仓库的跟目录), 替换成你要删除的文件便可.spa

若是你要删除的文件不少, 能够写进一个.sh文件批量执行, 若是文件或路径里有中文, 因为MinGW或CygWin对中文路径设置比较麻烦, 你可使用通配符*号, 例如: sound/music_*.mp3, 这样就把sound目录下以music_开头的mp3文件都删除了.code

例如这样, del-music-mp3.sh:htm

复制代码
#!/bin/bash

# git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch projects/Moon.mp3' --prune-empty --tag-name-filter cat -- --all
# git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch sound/Music_*.mp3' --prune-empty --tag-name-filter cat -- --all
复制代码

 若是你看到相似下面这样的, 就说明删除成功了:blog

Rewrite 48dc599c80e20527ed902928085e7861e6b3cbe6 (266/266)
# Ref 'refs/heads/master' was rewritten

若是显示 xxxxx unchanged, 说明repo里没有找到该文件, 请检查路径和文件名是否正确.

注意: 补充一点, 若是你想之后也不会再上传这个文件或文件夹, 请把这个文件或文件夹添加到.gitignore文件里, 而后再push你的repo.

步骤二: 推送咱们修改后的repo

以强制覆盖的方式推送你的repo, 命令以下:

git push origin master --force

这个过程实际上是从新上传咱们的repo, 比较耗时, 虽然跟删掉从新建一个repo有些相似, 可是好处是保留了原有的更新记录, 因此仍是有些不一样的. 若是你实在不在乎这些更新记录, 也能够删掉重建, 二者也差不太多, 也许后者还更直观些.

执行结果相似下面:

复制代码
Counting objects: 4669, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (4352/4352), done.
Writing objects: 100% (4666/4666), 35.16 MiB | 51 KiB/s, done.
Total 4666 (delta 1361), reused 0 (delta 0)
To https://github.com/defunkt/github-gem.git
 + beb839d...81f21f3 master -> master (forced update)
复制代码

 步骤三: 清理和回收空间

虽然上面咱们已经删除了文件, 可是咱们的repo里面仍然保留了这些objects, 等待垃圾回收(GC), 因此咱们要用命令完全清除它, 并收回空间.

命令以下:

复制代码
rm -rf .git/refs/original/

git reflog expire --expire=now --all

git gc --prune=now
Counting objects: 2437, done.
# Delta compression using up to 4 threads. # Compressing objects: 100% (1378/1378), done. # Writing objects: 100% (2437/2437), done. # Total 2437 (delta 1461), reused 1802 (delta 1048)
git gc --aggressive --prune=now
Counting objects: 2437, done.
# Delta compression using up to 4 threads. # Compressing objects: 100% (2426/2426), done. # Writing objects: 100% (2437/2437), done. # Total 2437 (delta 1483), reused 0 (delta 0)
复制代码

注: 绿色字部分是命令执行后的结果.

 

如今你再看看你的.git目录文件大小是否是变小了.