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


当前回答

对于我刚刚发明并尝试的这种情况的一种生活哈克(这非常好):

git add .
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 中的案例差异。


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

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

#!/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 清洁命令不会用我的 git 版本 2.9.0.windows.1 删除未追踪的文件。

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

git-clean 是你正在寻找的,它被用来从工作树中删除未追踪的文件。

我喜欢使用 git stash 命令,以后你可以得到 stashed 文件和更改. git clean 也是一个很好的选择,但完全取决于你的要求. 这里是 git stash 和 git clean 的解释,7.3 Git 工具 - Stashing 和 Cleaning