git - 如何将 HEAD 移回以前的位置? (分离头)和撤消提交

标签 git git-checkout git-reset git-revert git-reflog

在 Git 中,我试图通过 merge 到另一个分支然后通过以下方式将 HEAD 重置到之前的位置来执行 squash commit:

git reset origin/master

但我需要走出这一步。如何将 HEAD 移回之前的位置?

我有我需要将其移动到的提交的 SHA-1 片段 (23b6772)。我怎样才能回到这个提交?

最佳答案

在回答之前,让我们添加一些背景,解释一下这个HEAD是什么是。

First of all what is HEAD?

HEAD只是对当前分支上当前提交(最新)的引用。
只能有一个 HEAD在任何给定时间(不包括 git worktree )。

HEAD的内容存储在 .git/HEAD 中它包含当前提交的 40 字节 SHA-1。


detached HEAD

如果你不在最新的提交上——意思是HEAD指向历史上的先前提交,它被称为 detached HEAD

Enter image description here

在命令行上,它将看起来像这样 - SHA-1 而不是自 HEAD 以来的分支名称不指向当前分支的尖端:

Enter image description here

Enter image description here


关于如何从分离的 HEAD 中恢复的几个选项:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits to go back

这将 check out 指向所需提交的新分支。
此命令将 checkout 给定的提交。
此时,您可以创建一个分支,并从这里开始工作。

# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# Create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

您始终可以使用 reflog以及。
git reflog 将显示更新 HEAD 的任何更改并检查所需的 reflog 条目将设置 HEAD回到这个提交。

每次修改 HEAD 时,reflog 中都会有一个新条目

git reflog
git checkout HEAD@{...}

这会让你回到你想要的提交

Enter image description here


git reset --hard <commit_id>

“移动”您的 HEAD 回到所需的提交。

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • 注意:( Since Git 2.7 ) 您也可以使用 git rebase --no-autostash

enter image description here


git revert <sha-1>

“撤消”给定的提交或提交范围。
重置命令将“撤消”给定提交中所做的任何更改。
将提交带有撤消补丁的新提交,而原始提交也将保留在历史记录中。

# Add a new commit with the undo of the original one.
# The <sha-1> can be any commit(s) or commit range
git revert <sha-1>

此模式说明了哪个命令执行什么操作。
如您所见,reset && checkout修改 HEAD .

Enter image description here

关于git - 如何将 HEAD 移回以前的位置? (分离头)和撤消提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34519665/

相关文章:

git - 以前修订的 check out 目录中的子目录不会在 Git 中消失?

git - checkout 到名称中包含 '&' 的分支

git - 我可以删除 git 提交但保留更改吗?

git - 我可以在本地 TFS 服务器中维护公共(public) github 存储库的(非公共(public))分支吗?

Git 申请与我

git checkout 版本,包括子模块

git - "git reset"和 "git checkout"有什么区别?

删除远程分支后 git upstream 消失了

git - `rebase' 导致的冲突数量是否真的少于 `merge' ?

git - 为什么有两种方法可以在 Git 中取消暂存文件?