如何从当前工作树中删除未追踪的本地文件?


当前回答

git clean -f -d -x $(git rev-parse --show-cdup)适用于干净的根目录,无论你在哪里呼叫它在仓库目录树内。

确保 -f、 -d、 -x 旗帜符合您的需求:

-d
       Remove untracked directories in addition to untracked files. If an
       untracked directory is managed by a different Git repository, it is
       not removed by default. Use -f option twice if you really want to
       remove such a directory.

-f, --force
       If the Git configuration variable clean.requireForce is not set to
       false, git clean will refuse to delete files or directories unless
       given -f, -n or -i. Git will refuse to delete directories with .git
       sub directory or file unless a second -f is given. This affects
       also git submodules where the storage area of the removed submodule
       under .git/modules/ is not removed until -f is given twice.

-x
       Don't use the standard ignore rules read from .gitignore (per
       directory) and $GIT_DIR/info/exclude, but do still use the ignore
       rules given with -e options. This allows removing all untracked
       files, including build products. This can be used (possibly in
       conjunction with git reset) to create a pristine working directory
       to test a clean build.

还有其他旗帜也可用,只需检查 git clean --help。

其他回答

oh-my-zsh 与 zsh 提供这些伟大的联盟通过 git 插件. 它们也可以在 bash 中使用。

gclean='git clean -fd' gpristine='git reset --hard && git clean -dfx'

gclean 除去未追踪的目录除了未追踪的文件. gpristine 硬重定义本地变更,删除未追踪的目录,未追踪的文件,不要使用从.gitignore (每个目录) 和 $GIT_DIR/info/exclude 阅读的默认忽略规则,但仍然使用与 -e 选项提供的忽略规则。

更好的方法是使用: git clean

git clean -d -x -f

这将删除未追踪的文件,包括目录(d)和由 git(x)忽略的文件。

此外,将 -f 论点替换为 -n 以进行干燥运行或 -i 为互动模式,它会告诉你什么将被删除。

用途: git clean [-d] [-f] [-i] [-n] [-q] [-e ] [-x♰ -X] [--]...

-q, --quiet           do not print names of files removed
-n, --dry-run         dry run
-f, --force           force
-i, --interactive     interactive cleaning
-d                    remove whole directories
-e, --exclude <pattern>
                      add <pattern> to ignore rules
-x                    remove ignored files, too
-X                    remove only ignored files

如果需要从特定子目录中删除未追踪的文件,

git clean -f {dir_path}

并结合的方式来删除未追踪的Dir/文件和被忽略的文件。

git clean -fxd {dir_path}

此后,您将仅在 git 状态中修改文件。

清除 git 存储库和所有子模块重复 以下命令将清除当前 git 存储库和所有子模块重复: (git clean -d -x -f& git submodule foreach --recursive git clean -d -x -f)