LoginSignup
0
0

【メモ】Gitで特定のディレクトリを管理下から外す

Last updated at Posted at 2024-02-17

はじめに

ローカルリポジトリでGitの支配下にしたディレクトリ内でGitで管理する必要のないディレクトリをストレージから消去せずにGitの管理下から外す方法について調べた時のメモです。

ディレクトリ構成

二つのディレクトリ「dir1」「dir2」とREADMEファイルが入っている練習用のディレクトリ。

$:~/github/test$ ls
dir1  dir2  README.md

ローカルリポジトリの状態は以下のよう。
「dir1」と「dir2」がGitの管理下に入っていますが、commitしていない状態です。
この状態から「dir2」だけをGitの管理下から外す方法を調べて実行しました。

$:~/github/test$ git status
On branch main
Your branch is up to date with 'origin/main'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
new file:   dir1/test.txt
new file:   dir2/test.txt

失敗例:rm -rfコマンド

色々調べてrmコマンドに-rfを付けて実行した場合です。

$:~/github/test$ git rm -rf dir2
rm 'dir2/test.txt'
$:~/github/test$ ls
dir1  README.md

「dir2」はGitの支配下から消えるのですが、lsコマンドで確認してみると、ストレージ上からも「dir2」ディレクトリが消えてしまいました。

$:~/github/test$ git status
On branch main
Your branch is up to date with 'origin/main'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
new file:   dir1/test.txt
new file:   dir2/test.txt

これでは、ディレクトリ化のファイルも削除してしまうことになるので、うまくGitの支配下からのみ削除するための別の方法を調べました。

成功例:rm --cachedオプションを使う方法

再び「dir2」ディレクトリを作り直した後、いろいろ外のサイトを見て回った結果、「--cached」オプションを付けると成功するということが分かりました。
以下は実行例です。
「git rm」コマンドを実行した後もストレージ上からは「dir2」ディレクトリは消えていません。

$:~/github/test$ git rm -r --cached dir2
rm 'dir2/test.txt'
$:~/github/test$ ls
dir1  dir2  README.md

「git status」でGitの管理状態を見ると「dir2」が管理下に入らず、「dir1」だけがcommitの対象になっていることが分かります。

$:~/github/test$ git status
On branch main
Your branch is up to date with 'origin/main'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
new file:   dir1/test.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)
dir2/

これで必要のないファイルまでをGitで管理することなく作業を進める方法を知ることができました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0