追跡されていないファイルを Git

Stewart Nguyen 2022年2月6日 Git Git Tracking
追跡されていないファイルを Git

この記事では、Git でファイルを追跡解除する方法を紹介します。

git リポジトリ内のファイルには、tracked または untracked の 2つの状態があります。

追跡されたファイルは、Git が知っているファイルです。

追跡されていないファイルは、作業リポジトリ内で作成されたが、git add コマンドを使用して追加されていないファイルです。

このシナリオを考えてみましょう。

cd ~ mkdir my-repo cd my-repo git init touch file.txt git add file.txt git commit -m 'First commit' 

Git は file.txt について知っているので、技術的には、file.txt が追跡されるようになりました。

後で、このファイル名を .gitignore に追加して、Git に file.txt(または誤ってコミットされたファイル)を無視するように指示します。

touch .gitignore echo 'file.txt' >> .gitignore git add .gitignore && git commit -m 'Ignore file.txt' 

どうなるでしょうか?

.gitignore をコミットした後、file.txt に変更を加えると、リポジトリインデックスにまだ存在しているため、file.txt が追跡されていることが git に表示されます。

$ echo 'qwe' > file.txt $ 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: file.txt  no changes added to commit (use "git add" and/or "git commit -a") 

Git でファイルの追跡を解除する

手順 1、次のコマンドを実行します。

$ git rm --cache file.txt rm 'file.txt' $ git st On branch master Changes to be committed:  (use "git restore --staged <file>..." to unstage) deleted: file.txt 
  • rm 追跡を停止し、ローカルリポジトリディレクトリからファイルを削除します。
  • --cache オプションは、rm コマンドがファイルをインデックスからのみ削除し、ローカルリポジトリからファイルを削除しないことを指定します

git rm --cache file.txt は、リポジトリインデックスから削除することで file.txt の追跡を停止しますが、ファイルはそのまま保持します。

$ git commit -m 'Remove file.txt from tracking' [master 4697164] Remove file.txt from tracking  1 file changed, 0 insertions(+), 0 deletions(-)  delete mode 100644 file.txt 

今後、Git は file.txt に加えられた変更を追跡しません。

$ echo '123' > file.txt $ git st On branch master nothing to commit, working tree clean 
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe

関連記事 - Git Tracking