學習 Git - 有些檔案想被 Git 忽略


Posted by Calon on 2022-05-13

有時候工作目錄裡面會有一些金鑰或是密碼等比較機密的東西,亦或是程式每次編譯都會產生的一些暫存檔等等,如果使用 git add 去避開加入這些不想要放進 Git 裡面被備份的檔案當檔案一多時又很麻煩,有沒有比較好一點的方法?
答案是有的,我們可以建立一個 .gitignore 檔案來設定不想要被備份的檔案:

$ git .gitignore

我們在工作目錄新增一個 .env 檔案,假設我們在這個檔案裡面有我們的金鑰,所以不希望此檔案被備份時我們只要在剛剛新增的 .gitignore 裡面加入 .env:

# 忽略 .env
.env

我們可以使用 git status 來查看檔案追蹤的狀態:

$ git status
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)

未被追蹤的檔案只有我們剛剛新增的 .gitignore 而已。
除了當前目錄的檔案以外,也可以忽略子目錄的檔案,我們希望 configs 目錄裡面的 password.txt 檔案也被忽略:

# 忽略 configs 目錄裡的 password.txt
configs/password.txt

# 也可以只設定檔案名稱
password.txt

其他一些設定:

# 忽略所有 .yml 檔案
*.yml

# 忽略所有包含 password 開頭的檔案
password*

而如果哪天想要這些檔案被 Git 備份時只要把它們從 .gitignore 裡面移除就行了。

為什麼我設定了 .gitignore 後還是沒效果?

如果檔案在設定 .gitignore 前就對它有使用 git add,即使加入 .gitignore 也還是會出現以下訊息:

$ git status
Changes to be committed:
  (use "git restore --staged <file>..." to discard changes in working directory)
      new file: configs/password.txt

如果是已經提交 commit 後加入的,之後修改後再用 git status 檢查狀態:

$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)

  modified:   config/database.yml

不管哪個都沒有被 Git 忽略,不是說好在 .gitignore 裡面的檔案會被忽略嗎?
這是因為在設定 .gitignore 之前檔案就已經被 Git 追蹤了,如果是只有被加入暫存區並且還沒被提交 commit 過的檔案可以使用 git restore 從暫存區移出:

$ git restore --staged 檔案

如果已經提交 commit 的話,則是使用 git rm 並帶上參數 --cached,這樣可以讓檔案不再被 Git 追蹤並保留在工作目錄:

$ git rm 檔案 --cached

參考資料

#Git







Related Posts

Day 75

Day 75

Day04 LINE - Messaging API

Day04 LINE - Messaging API

2. Factory Method

2. Factory Method


Comments