有些時候不當心上傳了一些敏感文件(例如密碼), 或者不想上傳的文件(沒及時或忘了加到.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, 命令以下:
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目錄文件大小是否是變小了.