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


当前回答

用途: 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 - 从工作树中删除未追踪的文件 同步 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 中的案例差异。


注意: 首先,导航到目录并检查您要清理的分支。

-i 互动模式,它会告诉你什么将被删除,你可以从列表中选择一个操作。

清理文件只有 [文件不会列出并不会清理]: $ git clean -i 清理文件和文件夹: $ git clean -d -i

D 包括目录。


如果您从列表中选择 c 将删除未跟踪的文件/文件夹,并将删除您删除的文件/文件夹。

例如: 如果您在远程中重组文件夹并将更改拖到本地计算机上,则由其他人创建的文件/文件夹将最初在过去的文件夹和您重组的新文件夹中。

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

git clean -i

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

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

git iclean

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

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

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

#!/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 stash and git stash drop, try these three commands in this order in order to remove all untracked files. 通过添加所有这些未追踪的文件到 git 并 stashing 它们将移动所有这些未追踪的文件到 stash 列表并下载顶部一个,即, stash@{0} 将从 stash 列表中删除所有未追踪的文件。