rmを使わず git clean で管理外ファイルを一括削除する
rmコマンドで消したり、色々横着していたのですが、最近ちゃんとgitコマンドでやれることを知りました。 git cleanコマンドを使う まずは git clean を dry run で試します。 dry runで様子 […]
広告ここから
広告ここまで
目次
rmコマンドで消したり、色々横着していたのですが、最近ちゃんとgitコマンドでやれることを知りました。
git cleanコマンドを使う
まずは git clean を dry run で試します。
dry runで様子を見る
% git clean -dfn
Would remove .DS_Store
Would remove .github/
Would remove _content_strategy/
Would remove _qiita_api_dump/
Would remove cicd-test-lambda-typescript_config.yml
nオプションを外すと、削除される
% git clean -df
Removing .DS_Store
Removing .github/
Removing _content_strategy/
Removing _qiita_api_dump/
Removing cicd-test-lambda-typescript_config.yml
Removing ledger/
Removing public/0145e34c14e5faed64a6.md
Removing public/030e63184127e4075b0c.md
Removing public/0ab248ff3cddf9cb6210.md
Removing public/0c7ba3c7d69bcfcc9a9c.md
.gitignoreされているファイルも掃除したい場合
% git clean -dfxn
Would remove node_modules/
Would remove public/
-f が必要な理由と、-x / -X の違い
-f を付けないと、git clean は削除を拒否します。デフォルトで clean.requireForce という設定が有効になっていて、これが -n なしでの実行を止める安全装置になっています。dry run を挟まずに -df をいきなり叩くと、消したくないファイルまで一緒に消えるので注意が必要です。
もう一つ、-x と大文字の -X は別物です。-x は .gitignore の無視ルールを外して全部削除対象にしますが、-X は無視されているファイルだけを削除します。打ち間違えると意図した範囲と違う削除になります。
まとめ
rm で個別に消すよりも、git clean の dry run から入れば、untracked ファイルも ignore 済みファイルも同じ手順でまとめて確認しながら削除できます。