如何仅还原工作目录中的更改

Ste*_*sku 6 git

我有一个破坏的合并,我想恢复工作目录中的更改,以找出它被破坏的地方.我想保留索引,以便我可以添加修复程序并最终检入它们.实际上,我希望工作目录与HEAD相同但不修改索引.这基本上会将基于索引的反向补丁应用于工作目录.这似乎与a相反git reset.

你是如何用git做的?

Ste*_*eve 5

您可以提交索引,重置工作目录,然后重置提交.

$ git commit -m "blah"
$ git reset --hard
$ git reset --soft HEAD^
Run Code Online (Sandbox Code Playgroud)

编辑: 我似乎误解了原来的问题.

要在不干扰索引的情况下将工作树重置为HEAD,请执行以下操作:

$ git checkout -- .
$ git diff --cached | git apply --reverse
Run Code Online (Sandbox Code Playgroud)

(看起来@Brice已经给出了这个答案.)


Bri*_*ice 5

我正在查看一个做同样事情的简单命令,但没有。尽管您在问题中说明了正确的方法:

这基本上会将基于索引的反向补丁应用到工作目录。

所以答案很简单:

git diff --no-color --staged | git apply --reverse
Run Code Online (Sandbox Code Playgroud)

因此无需提交任何内容,只需应用索引的反向即可。

请注意,如果工作目录中的某些更改未暂存/在索引中,则不会以这种方式逆转。

如果要恢复工作目录中除索引本身之外的所有内容(甚至未编入索引的更改和新文件),请先运行以下命令:

git stash save --include-untracked --keep-index
Run Code Online (Sandbox Code Playgroud)

如果您不打算重复使用它,您可以在之后删除它:

git stash drop
Run Code Online (Sandbox Code Playgroud)

如果要恢复除未跟踪文件(不在索引中的新文件)之外的所有内容,
请先执行以下操作:

git checkout .
Run Code Online (Sandbox Code Playgroud)

总结一下这里有几个 bash 函数:

function git-unapply-index {
    git diff --no-color --staged | which git apply --reverse
}

function git-revert-workdir-keep-untracked {
    git checkout .
    git-unapply-index
}

function git-revert-workdir-all {
    git stash save --include-untracked --keep-index
    git stash drop
    git-unapply-index
}
Run Code Online (Sandbox Code Playgroud)


Hau*_*eth 1

你有没有尝试过git checkout <commit>?

\n\n

片段git help checkout:

\n\n
git checkout [<branch>], git checkout -b|-B <new_branch> [<start point>], git checkout [--detach] [<commit>]\n       This form switches branches by updating the index, working tree, and HEAD to reflect the specified branch or commit.\n\n       If -b is given, a new branch is created as if git-branch(1) were called and then checked out; in this case you can use the --track or --no-track\n       options, which will be passed to git branch. As a convenience, --track without -b implies branch creation; see the description of --track below.\n\n       If -B is given, <new_branch> is created if it doesn\xe2\x80\x99t exist; otherwise, it is reset. This is the transactional equivalent of\n\n           $ git branch -f <branch> [<start point>]\n           $ git checkout <branch>\n\n       that is to say, the branch is not reset/created unless "git checkout" is successful.\n
Run Code Online (Sandbox Code Playgroud)\n