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


当前回答

正常的 git 清洁命令不会用我的 git 版本 2.9.0.windows.1 删除未追踪的文件。

$ git clean -fdx     # doesn't remove untracked files
$ git clean -fdx *   # Append star then it works!

其他回答

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

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

#!/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 clean -i

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

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

git iclean

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

用途: 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 -fdx

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

git clean -fd 删除目录

git clean -fX 删除被忽略的文件

git clean -fx 删除被忽略和未被忽略的文件

可以使用上述所有选项,如

清洁 -fdXx

查看 git 手册 获取更多帮助