How to list files ignored by git that are currently staged or committed?
The documentation to ls-files
is not exactly clearly written, but it appears that the following simple alias does the job:
git config --global alias.showtrackedignored "ls-files -i --exclude-standard"
The above command creates an alias called showtrackedignored
. To use, run:
git showtrackedignored
and it will list all of the files in the current directory and subdirectories that are tracked but would be ignored if they weren't tracked.
Bug in git ls-files
Unfortunately, this doesn't work 100% reliably. Apparently Git does a good job of finding files that should not be ignored, but when searching for files that are ignored (the -i
option to git ls-files
), it doesn't list ignored files inside a directory if it's the directory that matches the ignore rules.
To work around this bug, try converting your ignore rules so that only files are matched, not directories (this isn't always possible).
(Thank you Christoph for discovering this bug and reporting it to the Git mailing list! Edit: A patch is in the works now and will make it into git 1.7.11.2 or later)
Alternative approach
Here's a different approach. It's far more complicated and might have broken corner cases.
git config --global alias.showtrackedignored '!
cd "${GIT_PREFIX}" &&
untracked_list=$(git rev-parse --git-dir)/ignored-untracked.txt &&
git ls-files -o -i --exclude-standard >"${untracked_list}" &&
GIT_INDEX_FILE="" git ls-files -o -i --exclude-standard | grep -Fvxf "${untracked_list}" &&
rm -rf "${untracked_list}"'
The alias does the following:
-
cd
back to the directory wheregit showtrackedignored
was run from (Git runs shell-based aliases from the toplevel directory, not the current directory; see the section onalias.*
ingit help config
) - Define a variable called
untracked_list
. This variable holds the path to a temporary file that will contain the list of currently ignored files. This temporary file is in the.git
directory. - Write the list of ignored files to
${untracked_list}
. - Tell Git to act as if the index is empty and list all the ignored files.
- Pipe that output to
grep
, which filters out the files that were written to${untracked_list}
. - Delete the temporary file
${untracked_list}
.
Drawbacks to this approach:
- It creates a temporary file in your
.git
directory. - It assumes you have a POSIX-compatible shell.
- It assumes you have a POSIX-compatible implementation of
grep
.
It also suffers from the same bug as the former alias.
Just going to leave this one here, based on Richard's answer:
git ls-files --cached -i --exclude-standard | xargs git rm --cached
This will delete every tracked file that is ignored by .gitignore
.