如何从工作目录删除所有更改,包括新的未跟踪文件。我知道git checkout -f这样做,但它不会删除自上次提交以来创建的新的未跟踪文件。

有人知道怎么做吗?


当前回答

你可以分两步完成:

恢复修改的文件:git checkout -f 删除不跟踪的文件:git clean -fd

其他回答

如果希望放弃所有更改,可以在.gitconfig中的别名中使用任何有效选项。例如:

[alias]
    discard = "!f() { git add . && git stash && git stash drop stash@{0}; }; f"

用法:git discard

对于所有被跟踪的非暂存文件使用:

git checkout -- .

的。结尾很重要。

你可以替换。子目录名,可仅清除项目的特定子目录。这里专门讨论了这个问题。

git reset --hard # removes staged and working directory changes

## !! be very careful with these !!
## you may end up deleting what you don't want to
## read comments and manual.
git clean -f -d # remove untracked
git clean -f -x -d # CAUTION: as above but removes ignored files like config.
git clean -fxd :/ # CAUTION: as above, but cleans untracked and ignored files through the entire repo (without :/, the operation affects only the current directory)

要查看将事先删除的内容,而不实际删除它,请使用-n标志(这基本上是一个测试运行)。当你准备实际删除时,然后删除-n标志:

Git clean -nfd

你可以分两步完成:

恢复修改的文件:git checkout -f 删除不跟踪的文件:git clean -fd

另一种解决方案是提交更改,然后删除这些提交。这在一开始并没有立即的好处,但它提供了以块提交的可能性,并为备份创建了一个git标记。

你可以在当前分支上这样做:

git add (-A) .
git commit -m"DISCARD: Temporary local changes"
git tag archive/local-changes-2015-08-01  # optional
git revert HEAD
git reset HEAD^^

或者你可以在分离的HEAD上做。(假设你从BRANCHNAME分支开始):

git checkout --detach HEAD
git add (-A) .
git commit -m"DISCARD: Temporary local changes"
git tag archive/local-changes-2015-08-01  # optional
git checkout BRANCHNAME

然而,我通常做的是在块中提交,然后将一些或所有提交命名为“DISCARD:…”。然后使用交互式rebase删除坏的提交并保留好的提交。

git add -p  # Add changes in chunks.
git commit -m"DISCARD: Some temporary changes for debugging"
git add -p  # Add more stuff.
git commit -m"Docblock improvements"
git tag archive/local-changes-2015-08-01
git rebase -i (commit id)  # rebase on the commit id before the changes.
  # Remove the commits that say "DISCARD".

这是更详细的,但它允许准确地检查您想要丢弃的更改。

git lol和git lola快捷键对这个工作流非常有帮助。