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


当前回答

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 是你正在寻找的,它被用来从工作树中删除未追踪的文件。

这可以用一个阴影脚本进行,我使用这个脚本列出什么将被删除,然后让我确认操作。

这是有用的,因为有时我有插件或其他文件我会喜欢检查之前删除一切。

#!/bin/bash
readarray -t -d '' FILES < <(git ls-files -z --other --directory)
if [ "$FILES" = "" ]; then
    echo  "Nothing to clean!"
    exit 0
fi
echo -e "Dirty files:\n"
printf '  %s\n' "${FILES[@]}"
DO_REMOVE=0
while true; do
    echo ""
    read -p "Remove ${#FILES[@]} files? [y/n]: " choice
    case "$choice" in
        y|Y )
            DO_REMOVE=1
            break ;;
        n|N )
            echo "Exiting!"
            break ;;
        * ) echo "Invalid input, expected [Y/y/N/n]"
            continue ;;
    esac
done

if [ "$DO_REMOVE" -eq 1 ];then
    echo "Removing!"
    for f in "${FILES[@]}"; do
        rm -rfv -- "$f"
    done
fi

删除未追踪的文件的简单方法

要删除所有未追踪的文件,简单的方式是先添加所有文件并重新设置下面的复制文件。

git add --all
git reset --hard HEAD

git clean -f 从工作目录中删除未追踪的文件。

我在我的博客中包含了一些基本内容, git-intro-basic-commands

如果未追踪的目录是自己的 git 存储库(例如子模块),您需要使用 -f 两次:

清洁 -d -f -f