Git Ignore 和 .gitignore
Git Ignore
當您與其他人員共享程式碼時,通常會有一些檔案或專案的一部分您不希望共享。
示例
- 日誌檔案
- 臨時檔案
- 隱藏檔案
- 個人檔案
- 等等。
Git 可以使用 `.gitignore` 檔案指定哪些檔案或專案部分應被 Git 忽略。
Git 不會跟蹤 `.gitignore` 中指定的檔案和資料夾。但是,`.gitignore` 檔案本身**會被** Git 跟蹤。
建立 .gitignore
要建立 `.gitignore` 檔案,請轉到本地 Git 的根目錄並建立它。
示例
touch .gitignore
現在使用文字編輯器開啟該檔案。
我們只新增兩個簡單的規則:
- 忽略所有具有 `.log` 副檔名的檔案。
- 忽略名為 `temp` 的任何目錄中的所有檔案。
示例
# 忽略所有 .log 檔案
*.log
# 忽略名為 temp 的任何目錄中的所有檔案
temp/
現在,所有 `.log` 檔案以及 `temp` 資料夾中的任何內容都將被 Git 忽略。
注意: 在這種情況下,我們使用一個 `.gitignore` 檔案,該檔案適用於整個儲存庫。
也可以在子目錄中使用額外的 `.gitignore` 檔案。這些檔案僅適用於該目錄內的檔案或資料夾。
.gitignore 檔案規則
以下是匹配 `.gitignore` 檔案中模式的一般規則:
模式 | 解釋/匹配 | 示例 |
---|---|---|
空白行將被忽略。 | ||
# 文字註釋 | 以 # 開頭的行將被忽略。 | |
name | 所有名為 `name` 的檔案、名為 `name` 的資料夾,以及任何名為 `name` 的資料夾中的檔案和資料夾。 | /name.log /name/file.txt /lib/name.log |
name/ | 以 / 結尾表示該模式是針對資料夾的。匹配任何名為 `name` 的資料夾中的所有檔案和資料夾。 | /name/file.txt /name/log/name.log 不匹配 /name.log |
name.file | 所有名為 `name.file` 的檔案。 | /name.file /lib/name.file |
/name.file | 以 / 開頭表示該模式僅匹配根資料夾中的檔案。 | /name.file 不匹配 /lib/name.file |
lib/name.file | 指定特定資料夾中檔案的模式始終是相對於根目錄的(即使您沒有以 / 開頭)。 | /lib/name.file 不匹配 name.file /test/lib/name.file |
**/lib/name.file | 以 ** 開頭,然後是 /,表示它匹配儲存庫中的任何資料夾,而不僅僅是根目錄。 | /lib/name.file /test/lib/name.file |
**/name | 所有名為 `name` 的資料夾,以及任何名為 `name` 的資料夾中的檔案和資料夾。 | /name/log.file /lib/name/log.file /name/lib/log.file |
/lib/**/name | 位於 `lib` 資料夾內的所有名為 `name` 的資料夾,以及任何名為 `name` 的資料夾中的檔案和資料夾。 | /lib/name/log.file /lib/test/name/log.file /lib/test/ver1/name/log.file 不匹配 /name/log.file |
*.file | 所有副檔名為 `*.file` 的檔案。 | /name.file /lib/name.file |
*name/ | 所有以 `name` 結尾的資料夾。 | /lastname/log.file /firstname/log.file |
name?.file | ? 匹配**單個**非特定字元。 | /names.file /name1.file 不匹配 /names1.file |
name[a-z].file | [範圍] 匹配指定範圍內的**單個**字元(在此示例中,為 a-z 範圍內的字元,也可能包含數字)。 | /names.file /nameb.file 不匹配 /name1.file |
name[abc].file | [集合] 匹配指定字元集中的**單個**字元(在此示例中,為 a、b 或 c)。 | /namea.file /nameb.file 不匹配 /names.file |
name[!abc].file | [!集合] 匹配**除**指定字元集(在此示例中為 a、b 或 c)之外的**單個**字元。 | /names.file /namex.file 不匹配 /namesb.file |
*.file | 所有副檔名為 `*.file` 的檔案。 | /name.file /lib/name.file |
name/ !name/secret.log |
! 表示否定或排除。匹配任何名為 `name` 的資料夾中的所有檔案和資料夾,除了 `name/secret.log`。 | /name/file.txt /name/log/name.log 不匹配 /name/secret.log |
*.file !name.file |
! 表示否定或排除。所有副檔名為 `*.file` 的檔案,除了 `name.file`。 | /log.file /lastname.file 不匹配 /name.file |
*.file !name/*.file junk.* |
在否定之後新增新模式將重新忽略之前被否定的檔案。 所有副檔名為 `*.file` 的檔案,除了 `name` 資料夾中的檔案。除非檔名是 junk。 |
/log.file /name/log.file 不匹配 /name/junk.file |
本地和個人 Git 忽略規則
也可以忽略檔案或資料夾,但不在分散式的 `.gitignore` 檔案中顯示。
這些型別的忽略規則指定在 `.git/info/exclude` 檔案中。它的工作方式與 `.gitignore` 相同,但不會顯示給其他人。