Search code examples
gitgitignore

Delete all files already added to git repository based on .gitignore


I tried deleteting all files already added to git repository exept files whoe not ignored by .gitignore

my workaround was:

  1. first i deleteted all files from the git repository,
  2. then i added files whoe not ignored by .gitignore.

In this way, files were deleted, which were added (identical) immediately thereafter. This is of course sub-optimal, not maximal performant. Is there a better solution for this more elegant?

here my attempts to the finish:

Administrator@SL5 MINGW64 /g/global-IntelliSense-everywhere-Nightly-Build (master)
$ git rm -r --cached .
rm 'AHK Studio Download Page.url'
rm 'ActionLists/ActionListNameFilter.inc.ahk'
rm 'ActionLists/ApplicationFrameWindow/ActionListNameFilter.inc.ahk'

Administrator@SL5 MINGW64 /g/global-IntelliSense-everywhere-Nightly-Build (master)
$ git commit -m 'Delete all the stuff'

Administrator@SL5 MINGW64 /g/global-IntelliSense-everywhere-Nightly-Build (master)
$ git rm -r -f .

Administrator@SL5 MINGW64 /g/global-IntelliSense-everywhere-Nightly-Build (master)
$ git commit -m 'Delete all the stuff'

I guess if I had used rm -r -f . instead of rm -r --cached . I would have had the same effect. After using rm -r --cached ., unfortunately there were still files in the repository that should not be there (regarding .gitignore).

git rm -r -f . and a commit+push deletes all from the git repository


Solution

  • git ls-files is the swiss-army knife of index-aware file listing.

    git ls-files --exclude-standard -ci 
    

    will list every file that's cached aka staged aka indexed aka tracked and also marked to be ignored by auto-add, so you can

    git ls-files --exclude-standard -ci | git update-index --force-remove --stdin
    

    or to also delete from the worktree

    git ls-files --exclude-standard -ciz | xargs  -r0 git rm -f 
    

    btw, I have git config --global alias.ls 'ls-files --exclude-standard, so for me the nuke-em is

    git ls -ciz|xargs -r0 rm -f