在回答之前,让我们添加一些背景知识,解释一下这是什么HEAD
is.
First of all what is HEAD?
HEAD
只是对当前分支上的当前提交(最新)的引用。
只能有一个HEAD
在任何给定时间(不包括git worktree
).
内容为HEAD
存储在里面.git/HEAD
它包含当前提交的 40 字节 SHA-1。
detached HEAD
如果您不是最新的提交 - 这意味着HEAD
指向历史中的先前提交,称为detached HEAD
.
在命令行上,它看起来像这样 - SHA-1 而不是分支名称,因为HEAD
不指向当前分支的尖端:
关于如何从分离的 HEAD 中恢复的一些选项:
git checkout https://git-scm.com/docs/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
这将检出指向所需提交的新分支。
此命令将签出给定的提交。
此时,您可以创建一个分支并从此时开始工作。
# 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 https://git-scm.com/docs/git-reflog
您可以随时使用reflog
以及。
git reflog
将显示更新的任何更改HEAD
并检查所需的引用日志条目将设置HEAD
回到这个提交。
每次修改 HEAD 时,都会在 HEAD 中产生一个新条目reflog
git reflog
git checkout HEAD@{...}
这会让你回到你想要的提交
git reset --hard <commit_id> https://git-scm.com/docs/git-reset
将您的 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.
- Note: (从 Git 2.7 开始 https://github.com/git/git/blob/master/Documentation/RelNotes/2.7.0.txt)您还可以使用
git rebase --no-autostash
以及。
git revert <sha-1> https://git-scm.com/docs/git-revert
“撤消”给定的提交或提交范围。
恢复命令将“撤消”给定提交中所做的任何更改。
将提交带有撤消补丁的新提交,同时原始提交也将保留在历史记录中。
# 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
.