忽略
就是某些檔案雖然在 git init 的資料夾中,但不想要被 git 加入追蹤。
像是一些重要的帳號密碼資訊、在程式編譯中產生的中間的過渡檔案等,
此時,只要在 .gitignore
檔案新增略過的規則即可,沒有該檔案的話可以自行新增。
# 假設他不存在
$ touch .gitignore
# 編輯該檔案
# 忽略 password.ini 檔案
password.ini
# 忽略 database 資料夾下的 mysql.ini 檔案
database/mysql.ini
# 忽略所有 db 資料夾中附檔名為 txt 的檔案
/db/*.txt
# 忽略所有附檔名是 py 的檔案
*.py
之後在新增檔案時符合 .gitignore
檔案內的忽略規則就會被略過,
比較特別的是 .gitignore
一旦新增就算沒有存到暫存區或提交也都有效。
我們已經新增了忽略規則檔案,但還沒有提交,讓我們來做個實驗。
$ git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
.gitignore
nothing added to commit but untracked files present (use "git add" to track)
# 因為沒有 add 也沒有 commit 接著測試看看該忽略的檔案會不會被忽略
$ touch password.ini
# 已經新增應該被忽略的檔案
$ git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
.gitignore
nothing added to commit but untracked files present (use "git add" to track)
從上面的紀錄中可以發現,提醒 Untracked files
依然只有 .gitignore
這就表示 password.ini 完全被忽略了。
闖關
在存到暫存區時加上 -f
就可以強行闖關,也就是雖然 .gitignore
有忽略規則,
但他會忽略這些忽略規則。
$ git add -f .
$ git status
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: .gitignore
new file: password.ini
從上面的紀錄可以看出 password.ini
依然被存到暫存區了,闖關成功。
忽略無效
有一個狀況雖然已經加了忽略規則,但該檔案依然沒被忽略,
這是因為 git 跟一般法律一樣有不溯既往的特性,
也就是說原本已經存在的檔案,現在加入忽略規則也對那些檔案無效,
上面的範例有效是因為 password.ini 是在忽略規則建立後台新增的。
那怎麼辦呢?就利用之前學到的 git rm 檔名 --cached
手動移除該檔案的追蹤,
這樣 .gitignore
的忽略規則就會開始對他們有效了。
另外,使用 git clean -X
可以把所有不被追蹤的檔案刪除。
$ git rm password.ini --cached
rm 'password.ini'
$ git clean -fX
Removing password.ini
$ git status
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: .gitignore
$ ls
hello.txt test.py
password.ini 被刪掉了,加上 -f
是強制執行的意思。
沒看到 .gitignore
是因為他是 .
開頭的隱藏檔,要使用 -a
列出全部才看得到。
空資料夾自動忽略
最後,提醒一下,在新增空資料夾時就算 add 與 commit 後也都不會被追蹤,
我們一直在強調檔案檔案,就是在告訴大家,git 是以檔案為單位來追蹤的,
所以資料夾一定要放個檔案才會被加入追蹤喔。