Git: set the tip of a branch to a particular commit

Ale*_*pov 1 git branch

Suppose one has a branch named my-branch with three commits like this:

aaa
bbb
ccc
Run Code Online (Sandbox Code Playgroud)

At first the tip of my-branch is pointing at aaa. If one does git reset --hard HEAD^ the tip will start pointing at bbb. The same command will cause the tip of my-branch to point to ccc. How can one point the tip again at aaa or bbb?

One option would be to checkout aaa or bbb (detach HEAD) and then checkout a new branch, say new-branch, delete my-branch and use the new one. I also suppose that something like git branch -f my-branch bbb should work, but when I try this, I get

fatal: Cannot force update the current branch.
Run Code Online (Sandbox Code Playgroud)

Any other ideas?

tor*_*rek 5

You can run git reset --hard <commit-ID> to re-re-adjust the current branch. Use the reflog to find the ID, if needed—or, even simpler, if the reflog says that this is (say) HEAD@{2}, just git reset --hard HEAD@{2} (note that each git reset renumbers the n in @{n}).

如果合并是快进合并git mergeFrancisco Puga 的答案中的方法也可以正常工作。(如果你选择了一个错误的,你会得到一个真正的合并,如果这是你想要的,这很好,否则你可以git reset --hard HEAD^撤消它。)同样,你可以给出原始 SHA-1 或 reflog 名称。作为额外奖励:

git merge --ff-only id

唯一的“向前滑动分支名称”(迈向一个新的尖状aaabbb),永远不会做一个“正规”的合并,所以这是一个很好的方式,以确保您使用的是适当的ID。