無視するファイルのチェックと組み合わせる
前のステップでは、git status
と git ls-files --others
を使用して追跡されていないファイルを特定する方法を学びました。しかし、一時ファイル、ビルド出力、または機密情報を含む設定ファイルのように、意図的に Git が追跡しないようにしたいファイルがある場合があります。Git では、これらのファイルを .gitignore
ファイルで指定することができます。
このステップでは、.gitignore
ファイルを作成し、それが git status
と git ls-files --others
の出力にどのように影響するかを確認します。
まず、~/project/my-time-machine
ディレクトリにいることを確認してください。
では、無視したいファイルを作成しましょう。temp.log
という名前にします。
echo "This is a temporary log file" > temp.log
再度 git status
を実行します。
git status
notes.txt
と temp.log
の両方が追跡されていないファイルとしてリストされているはずです。
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: message.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
notes.txt
temp.log
no changes added to commit (use "git add" and/or "git commit -a")
では、.gitignore
ファイルを作成し、temp.log
を追加しましょう。nano
エディタを使用してファイルを作成および編集します。
nano .gitignore
nano
エディタ内で、以下の行を入力します。
temp.log
Ctrl + X
を押し、次に Y
を押して保存し、Enter
を押してファイル名を確認します。
では、もう一度 git status
を実行します。
git status
今度は、temp.log
は「Untracked files:」のリストに表示されなくなるはずです。
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: message.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
notes.txt
no changes added to commit (use "git add" and/or "git commit -a")
Git はこれで temp.log
を無視するようになりました。git ls-files --others
がどのように影響を受けるかも確認してみましょう。
git ls-files --others
出力は現在 notes.txt
のみを表示するはずです。
notes.txt
デフォルトでは、git ls-files --others
は無視されるファイルをリストしません。通常、明示的に Git に無視するように指示したファイルを表示したくないため、これは望ましい動作です。
もし無視されるファイルを他の追跡されていないファイルと一緒に表示したい場合は、git ls-files --others
に --ignored
オプションを使用することができます。
git ls-files --others --ignored
出力には、追跡されていないファイルと無視されるファイルの両方が含まれるようになります。
.gitignore
notes.txt
temp.log
なお、.gitignore
自体は、追加してコミットするまでは追跡されていないファイルです。
.gitignore
の使い方を理解することは、リポジトリをきれいに保ち、実際のプロジェクトファイルに焦点を当てるために重要です。バージョン管理に含めるべきでないファイルが誤ってコミットされるのを防ぎます。