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


当前回答

这是我一直使用的:

git clean -fdx

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

其他回答

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 add .
git reset --hard HEAD

注意! 请确保在执行此事之前进行任何必要的更改(即使在未被拖动的文件中)。

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

git clean -i

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

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

git iclean

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

取消完整的更改 git clean -f -d

$ git clean -f -d
Removing client/app/helpers/base64.js
Removing files/
Removing package.json.bak

where 
-f is force 
-d is a directory 

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

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

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