ログってなんぼ

エンジニアのメモです

Git:.gitignoreに後から追記したファイルを一括で管理対象からはずす

ディレクトリ構成

こんな感じ

$ tree
.
├── need_1
│   └── need.txt
├── need_2
│   └── need_more.txt
└── no_need
    ├── irane.txt
    ├── majide_irane.txt
    └── mou_irane.txt

3 directories, 5 files

上記すべてが管理対象となっている状態

$ git ls-files --full-name
need_1/need.txt
need_2/need_more.txt
no_need/irane.txt
no_need/majide_irane.txt
no_need/mou_irane.txt

.gitignoreを書く

no_need/*

管理対象から外す

後からignoreした場合、そのままでは管理対象から外れてくれないのでgit rmを実行して管理対象から外します

$ git rm --cached no_need/irane.txt
rm 'no_need/irane.txt'

--cachedオプションをつけた場合、実際のファイルは削除されません。つけないとファイルも消えてしまうので注意

確認

$ git ls-files --full-name
need_1/need.txt
need_2/need_more.txt
no_need/majide_irane.txt
no_need/mou_irane.txt

no_need/irane.txt が管理対象から外れました

一括で処理する

ファイルが大量にある場合、ひとつひとつ作業をしていくのは大変面倒なので一括処理をします

一例ですが、git ls-filesのoptionを活用して一括処理してみます

Git - git-ls-files Documentation

$ git ls-files --full-name --ignored --exclude-standard
no_need/majide_irane.txt
no_need/mou_irane.txt

上記コマンドで、ignoreされているファイルのリストが取得できるので

$ git ls-files --full-name -i --exclude-from=.gitignore | xargs git rm --cached
rm 'no_need/majide_irane.txt'
rm 'no_need/mou_irane.txt'

これで一括処理出来ました

もっといい方法あるかな?(´・ω・`)

実用Git

実用Git

  • 作者: Jon Loeliger,吉藤英明(監訳),本間雅洋,渡邉健太郎,浜本階生
  • 出版社/メーカー: オライリージャパン
  • 発売日: 2010/02/19
  • メディア: 大型本
  • 購入: 7人 クリック: 287回
  • この商品を含むブログ (45件) を見る