0%

Git - 忽略特定檔案 .gitignore

前言

最近接手外包廠商的 code ,看別人的 code 怎麼寫的總是會有一些意外的收穫,也順便複習一下之前遇過的問題,並把它記錄下來。

第一個遇到的問題就是當我修改完成 code 準備要 commit 時,發現 Git 追蹤(track)了一些不應該 push 到 remote repository的東西。
像是 IntelliJ IDE的一些檔案或是 log 等的東西,所以我決定加個.gitignore

加入.gitignore

STEP1. 新增.gitignore 檔案

1
$ touch .gitignore

STEP2. 設定要忽略的檔案

1
2
3
4
5
6
## idea
.idea/*.xml
.idea/.name

## log
logs/

像我這樣設定的話就是忽略idea目錄下.xml.name結尾的檔案,以及忽略log目錄下的所有東西。

結果

在新增.gitignore 這個過濾條件後新增的檔案,如果符合上面的的規則就 Git 就不會去追蹤他

但在新增.gitignore 這個過濾條件前新增的檔案,如果沒有額外處理的話還是會被追蹤。

處理新增.gitignore 這個過濾條件前新增的檔案

1
2
3
4
5
6
7
8
# 清除本機 Git 的快取,相當於將所有檔案移除 Git 的追蹤,但沒有刪除檔案
$ git rm -r --cached .

# 重新加入 Git 追縱,這時會套用 .gitignore 設定
$ git add .

# commit上去時會忽略那些設定在 .gitignore 的檔案
$ git commit -m 'update .gitignore'

其他

除了我在這個狀況裡遇到的那些不想被 push 到 remote repository的東西外,一般也不會把機密資料、java編譯後的檔案(target目錄下的東西)與編輯器的檔案等給放上去。

GitHub 上面也有提供各種專案的 .gitignore 範本,可以參考這個專案進行設定 Github - A collection of useful .gitignore templates

參考資料

  1. https://poychang.github.io/gitignore-and-delete-untracked-files/
  2. https://gitbook.tw/chapters/using-git/ignore.html