如何在 Git 倉庫中忽略之前已提交的檔案?
.gitignore 檔案不適用於已提交的檔案。要忽略意外暫存或提交的檔案的更改,應執行以下操作:
步驟 1 - 從暫存區刪除這些檔案或目錄
步驟 2 - 提交倉庫中的更改
步驟 3 - 在 .gitignore 檔案中新增這些檔案或目錄的路徑
步驟 4 - 提交對倉庫的更改
讓我們透過一個示例來理解這一點:
在工作目錄中建立一個名為“bin”的資料夾。在資料夾中新增一個名為“temp.bin”的檔案,並在其中新增一些內容,然後提交更改。
$ mkdir bin //create a directory $ echo hello>bin/temp.bin //create a file temp.bin in the directory $ git add bin/temp.bin //record the change in the staging area $ git commit −m ‘add temp.bin’ //commit the change
提交命令的輸出表明該檔案已永久新增到倉庫中。
[master dd1a3a8] add tremp.bin 1 file changed, 1 insertion(+) create mode 100644 bin/temp.bin
在檔案“temp.bin”中新增一行。使用 git status 命令檢查此更改是否被跟蹤。
$ echo hello again > bin/temp.bin $ git status
輸出如下所示,表明更改已被跟蹤。
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 : bin/temp.bin No changes added to commit
現在假設在稍後的某個時間點,我們決定應該忽略對“bin”資料夾的更改。將“bin”資料夾新增到 .gitignore 檔案將沒有任何效果,因為該檔案已提交。為了忽略對已提交檔案的更改,請執行以下操作:
步驟 1 - 從暫存區刪除“bin”資料夾 - 必須記住,已提交的檔案不會自動從暫存區刪除。因此,讓我們首先從暫存區刪除該檔案。這可以透過使用 git rm --cached -r 命令來實現。此命令的語法為:
git rm −−cached −r <file−name> OR git rm −−cached −r <folder−name>
現在讓我們刪除“bin”資料夾。
$ git rm −−cached −r bin/
以上命令的輸出顯示在螢幕截圖中:
rm ‘bin/temp.bin’
使用git ls-files驗證該資料夾是否已從暫存區刪除。
$ git ls−files
輸出表明該資料夾已從暫存區刪除。
.gitignore
步驟 2 - 提交倉庫中的更改
$ git commit m ‘deleted bin folder from tracking’
驗證輸出以確認更改已提交。
dell@DESKTOP−N961NR5 MINGW64 /e/tut_repo (master) $ git commit −m bin 'deleted bin folder from tracking changes' [master 593aacd] deleted bin folder from tracking changes 1 file changed, 1 deletion (−) delete mode 100644 bin/temp. bin
步驟 3 - 在.gitignore 檔案中新增“bin”資料夾。我們假設.gitignore 檔案已存在。
$ echo bin/ >>.gitignore
現在將更改新增到暫存區。
$ git add .gitignore
步驟 4 - 提交對倉庫的更改
$ git commit −m ‘modified .gitignore to add bin/’
步驟 5 - 要驗證 Git 是否正在跟蹤“bin”資料夾,讓我們對“temp.bin”檔案進行更改,然後執行git status命令。
$ hello again from TutorialsPoint >>bin/temp.bin $ git status
輸出證明 Git 已完全忽略了在“bin”資料夾中執行的更改。
On branch master Nothing to commit, working tree clean