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


当前回答

在运行清洁命令之前,总是使用 -n,因为它会向您展示哪些文件会被删除。

通常情况下,当没有确定的情况下,Git Clean 不会返回未跟踪的目录,以避免删除太多。 指定 -d 以便返回此类目录。 如果任何路径是确定的, -d 是无关紧要的; 所有未跟踪的文件符合确定的路径(除非在 --force 中提到的未跟踪的Git目录)将被删除。

git clean -n -d 
git clean -n -d -f

git clean -d -f

默认情况下, git clean 只会删除未追踪的文件,这些文件不会被忽视. 任何符合您的.gitignore 或其他 ignore 文件中的模式的文件将不会被删除. 如果您想要删除这些文件,您可以将 -x 添加到清洁命令。

git clean -f -d -x

git clean -x -i

If you are not 100% sure that deleting your uncommitted work is safe, you could use stashing instead
git stash --all

git stash push --keep-index

呼叫 git stash 没有任何论点,相当于 git stash push。

git stash push -m "name your stash" // before git stash save (deprecated)

git stash drop // or clean

要查看关于如何使用 stash 的完整指示,请参见此 如何在 git 中以名称命名和获取 stash?

其他回答

git-clean - 从工作树中删除未追踪的文件

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。

更好的方法是使用: git clean

git clean -d -x -f

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

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

我很惊讶以前没有人提到这一点:

git clean -i

它是互动的,你会得到一个快速的概述,什么将被删除,为您提供包含 / 排除受影响的文件的可能性。

你必須在 -d 如果你也想照顧空的文件夾。

git iclean

说到这一点,对互动命令的额外持有可能令人兴奋的经验丰富的用户,如今我只使用已经提到的 git clean -fd

这是我一直使用的:

git clean -fdx

对于一个非常大的项目,你可能想运行它几次。