複数のファイルとディレクトリの操作
Git のキャッシュから単一ファイルを削除する方法がわかったので、複数のファイルやディレクトリ全体を削除するなど、より複雑なシナリオを検討しましょう。
実践のためのファイルの追加
まず、練習用にさらにいくつかのファイルとディレクトリ構造を作成しましょう。
- ディレクトリといくつかの追加ファイルを作成します。
## Create a directory for temporary files
mkdir temp
## Create some files in the temp directory
echo "This is a temporary file" > temp/temp1.txt
echo "Another temporary file" > temp/temp2.txt
## Create another log file in the main directory
echo "2023-01-02: System updated" > system.log
- これらの新しいファイルを Git の追跡に追加します。
git add .
- 変更をコミットします。
git commit -m "Add temporary files and system log"
- Git がすべてのファイルを追跡していることを確認します。
git ls-files
次のように表示されるはずです。
app.log
config.ini
sample.txt
system.log
temp/temp1.txt
temp/temp2.txt
Git のキャッシュから複数のファイルを削除する
次に、すべてのログファイルと temp ディレクトリ全体を Git の追跡から削除するとします。
- ログファイルを Git の追跡から削除します。
git rm --cached system.log
- temp ディレクトリ内のすべてのファイルを再帰的に削除します。
git rm --cached -r temp/
ここで -r フラグは重要です。これは、Git にディレクトリ内のすべてのファイルをそのキャッシュから再帰的に削除するように指示します。
- ステータスを確認します。
git status
ログファイルと temp ディレクトリ内のすべてのファイルの両方が、Git の追跡システムからの削除のためにステージングされていることがわかります。
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
deleted: system.log
deleted: temp/temp1.txt
deleted: temp/temp2.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
system.log
temp/
- これらの変更をコミットします。
git commit -m "Remove logs and temp directory from Git tracking"
- Git がこれらのファイルを追跡しなくなったことを確認します。
git ls-files
これで、次だけが表示されるはずです。
app.log
config.ini
sample.txt
ただし、すべてのファイルはまだローカルディレクトリに存在します。
ls -la
ls -la temp/
.gitignore を使用して不要なファイルの追跡を防止する
ファイルを Git の追跡から削除したので、誤って再び追加されないように、.gitignore ファイルを設定しましょう。
.gitignore ファイルを作成します。
nano .gitignore
- 次のパターンをファイルに追加します。
## Ignore log files
*.log
## Ignore temp directory
temp/
-
保存して終了します (Ctrl+X、次に Y、次に Enter を押します)。
-
.gitignore ファイルを追加してコミットします。
git add .gitignore
git commit -m "Add .gitignore file"
これで、すべてのファイルを Git に追加しようとしても、.gitignore ファイルが尊重され、指定されたパターンは追跡されません。
git add .
git status
ログファイルと temp ディレクトリが Git の追跡に追加されていないことがわかります。
これで、Git のキャッシュから複数のファイルとディレクトリを削除する方法、および .gitignore ファイルを使用して特定のファイルが将来追跡されないようにする方法を学びました。