1. 程式人生 > >git忽略版本庫中的檔案——.gitignore

git忽略版本庫中的檔案——.gitignore

背景

有些時候,工作目錄中的一些檔案沒有必要提交到版本庫中,如ide生成元資料檔案、程式編譯或解釋產生的中間檔案、源資料、密碼配置檔案等等。
為了解決這個問題,可以在git工作區的根目錄下建立一個特殊的.gitignore檔案,將要忽略的檔案寫進去,git就會忽略對這些檔案的版本控制。

.gitignore語法

GitHub上有一個開源庫(https://github.com/github/gitignore),包含了常見的程式語言在不同的開發背景下所需要忽略的檔案模板。我們可以在此基礎上增加自己的配置進行使用。
.gitignore的一般語法如下:

  • 使用標準的
    glob 模式
    匹配(支援*, ?, []等)。
  • #開頭註釋,會被 Git 忽略。
  • 以(/)開頭防止遞迴。
  • 以(/)結尾指定目錄。
  • 要忽略指定模式以外的檔案或目錄,可以在模式前加上驚歎號(!)取反。

示例:

# no .a files
*.a

# but do track lib.a, even though you're ignoring *.a files above
!lib.a

# only ignore the TODO file in the current directory, not subdir/TODO
/TODO

# ignore all files in the build/ directory
build/ # ignore doc/notes.txt, but not doc/server/arch.txt doc/*.txt # ignore all .pdf files in the doc/ directory doc/**/*.pdf