如何通过git ls-files --others列出空文件夹及--no-empty-directory用法咨询
Let's tackle your two questions one by one, based on your Git 1.8.3 environment and test case:
1. How to list empty folders with git ls-files --others?
First, it's important to understand a core Git behavior: Git doesn't track empty directories by design. The git ls-files --others command is meant to show untracked files, not directories—empty or otherwise. That's why your empty test12345 folder didn't show up in the output.
Since Git doesn't have a built-in flag to list empty directories directly via git ls-files, you'll need to combine it with system-level commands like find to achieve this. For example:
find . -type d -empty -not -path './.git/*'
This command scans your repository, finds all empty directories, and excludes the .git folder (which you don't want to interfere with).
2. What's the usage of --no-empty-directory?
As per the Git manual:
--no-empty-directory 不列出空目录,无--directory参数时无效。
Let's break this down clearly:
- The
--directoryflag is a strict prerequisite for--no-empty-directoryto work. By default,git ls-filesonly lists files, not directories. Adding--directorytells Git to include directories that contain untracked files in the output. - When paired with
--directory,--no-empty-directoryfilters out any empty directories from the results.
Here's a quick example to illustrate:
Suppose you have two directories:
dir_with_file: Contains an untracked filefoo.txtempty_dir: Has no files inside
Running git ls-files --others --directory would list both dir_with_file/ and foo.txt (behavior varies slightly by Git version, but directories with untracked files will appear). But if you run git ls-files --others --directory --no-empty-directory, only dir_with_file/ and foo.txt will show up—empty_dir gets excluded entirely.
Remember: Without the --directory flag, --no-empty-directory does nothing at all, as noted in the manual.
内容的提问来源于stack exchange,提问作者kittygirl

