还原暂存的更改,保留未暂存的更改

Revert staged changes, keep unstaged changes

我在 git 中有一些已暂存和未暂存的更改,以及一些未跟踪的文件。我想保留未暂存的更改和未跟踪的文件,并放弃已暂存的更改。

在命令行上执行此操作的最简单方法是什么?

I have some staged and some unstaged changes in git, as well as some untracked files. I would like to keep the uncommited changes and untracked files, and discard the commited changes.

正如您在评论中澄清的那样,您的意思是“...并丢弃 staged 更改”(而不是 committed 更改) .通常,您会使用 git reset 来撤消 git add。但在您的情况下,您希望保留未暂存的更改,因此:

git commit     # move staged to a commit, does not touch unstaged changes/unadded files

git checkout HEAD^    # checkout the previously committed version while keeping unstaged changes/unadded files   

git branch yourbranchname --force    # to grab the branch and move it back as well
git reset HEAD^

将 HEAD 重置为其父级,现在提交更改在索引中被丢弃但保留在工作树中。

git checkout -- paths_of_files_whose_changes_are_to_be_discarded_in_the_work_tree

放弃工作树中的更改。

还原未暂存的更改保留暂存的更改,请将此添加到您的~/.gitconfig:

[alias]
    revert-unstaged = "!sh -c '{ git commit -m=tmp && git reset --hard HEAD && git reset --soft HEAD^ || git reset --hard HEAD; } > /dev/null 2>&1; git status'"

然后您可以执行 git revert-unstaged,它执行以下操作:

  • 如果有暂存更改则创建本地提交

  • 使用 git reset --hard HEAD

  • 删除任何未暂存的更改
  • 如果暂存更改,还原本地提交以恢复它们

  • 运行 git status 新状态概览