要移动检出分支的分支指针,可以使用git reset——hard命令。但是如何移动未签出分支的分支指针指向不同的提交(保持所有其他东西,如跟踪远程分支)?


当前回答

git branch --force <branch-name> [<new-tip-commit>]

如果忽略new-tip-commit,则默认为当前提交。

New-tip-commit可以是一个分支名称(例如master, origin/master)。

其他回答

你也可以传递git reset——hard一个提交引用。

例如:

git checkout branch-name
git reset --hard new-tip-commit

我发现我经常做这样的事情:

假设这段历史

$ git log --decorate --oneline --graph
* 3daed46 (HEAD, master) New thing I shouldn't have committed to master
* a0d9687 This is the commit that I actually want to be master

# Backup my latest commit to a wip branch
$ git branch wip_doing_stuff

# Ditch that commit on this branch
$ git reset --hard HEAD^

# Now my changes are in a new branch
$ git log --decorate --oneline --graph
* 3daed46 (wip_doing_stuff) New thing I shouldn't have committed to master
* a0d9687 (HEAD, master) This is the commit that I actually want to be master

为了丰富讨论内容,如果你想将myBranch分支移动到当前提交,只需省略-f之后的第二个参数

例子:

吉特妙兰


我通常这样做,当我在一个分离的头部状态下重新设置:)

说实话,我很惊讶为什么没有人想到git push命令:

git push -f . <destination>:<branch>

点(.)引用本地存储库,您可能需要-f选项,因为目标可能“位于其远程对应对象的后面”。

虽然此命令用于在服务器中保存更改,但结果与将远程分支(<branch>)移动到与本地分支(<destination>)相同的提交完全相同。

打开文件.git/refs/heads/<your_branch_name>,并将存储在那里的散列更改为您想要移动分支头部的散列。只需编辑和保存文件与任何文本编辑器。只需确保要修改的分支不是当前活动的分支。

免责声明:可能不是一个明智的方法,但可以完成工作。

对于检出的分支,在你想要指向的提交在当前分支之前的情况下(除非你想撤销当前分支的最后一次提交,否则应该是这样),你可以简单地做:

git merge --ff-only <commit>

这是一个较软的git重置的替代方案——很难,如果你不是在上面描述的情况下,就会失败。

对一个未签出的分支做同样的事情,等价的是:

git push . <commit>:<branch>