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


当前回答

要删除未追踪的文件,您应该首先使用命令查看将受清洁影响的文件。

git clean -fdn

这将向您展示将被删除的文件列表. 现在实际上删除这些文件使用这个命令:

git clean -fd

其他回答

这是我一直使用的:

git clean -fdx

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

在运行清洁命令之前,总是使用 -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 add -A& git commit -m temp && git reset --hard HEAD^

这将首先完成您的所有变化,然后创建一个暂时的承诺,然后放弃它。

git-clean - 从工作树中删除未追踪的文件 同步 git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x♰ -X] [--] <path>... 描述 通过从当前目录开始,不受版本控制的文件重新删除工作树。


# Print out the list of files and directories which will be removed (dry run)
git clean -n -d

# Delete the files from the repository
git clean -f

注意后两个命令的 X 中的案例差异。


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。