在没有结账的情况下将其他分支重置为当前

Ale*_*ysh 100 git

我正在为我的Git工作流编写一些脚本.

我需要将其他(现有)分支重置为当前分支,而无需结帐.

之前:

 CurrentBranch: commit A
 OtherBranch: commit B
Run Code Online (Sandbox Code Playgroud)

后:

 CurrentBranch: commit A
 OtherBranch: commit A
Run Code Online (Sandbox Code Playgroud)

相当于

 $ git checkout otherbranch 
 $ git reset --soft currentbranch
 $ git checkout currentbranch
Run Code Online (Sandbox Code Playgroud)

(注意--soft:我不想影响工作树.)

这可能吗?

Col*_*ett 199

设置otherbranch为指向与currentbranch运行相同的提交

git branch -f otherbranch currentbranch
Run Code Online (Sandbox Code Playgroud)

-f(力)选项告诉git branch 是的,我真的要覆盖任何现有的otherbranch与新的一个参考.

文档:

-f
--force

如果已存在则重置为.没有-f git branch拒绝更改现有分支.

  • Imo,这应该是公认的答案.这大大改善了我的工作流程! (7认同)
  • 这是最简单的答案.谢谢! (5认同)
  • @FuadSaud那是因为你已经签出了`otherbranch`.这个SO问题具体是关于将*另一个*分支重置为不同的提交(即不重置签出的分支).你想要做的是用`git reset targetbranch`重置当前分支,强制当前分支指向`targetbranch`.添加`--hard`以强制工作树到该内容.或者`--soft`单独留下索引,只改变分支本身. (4认同)

P S*_*ved 77

您描述的工作流程并不等同:执行时,您reset --hard将丢失工作树中的所有更改(您可能想要创建它reset --soft).

你需要的是什么

git update-ref refs/heads/OtherBranch refs/heads/CurrentBranch
Run Code Online (Sandbox Code Playgroud)

  • 一个更好的方法是`git push.当前:other`.这可以在没有`refs/heads`(/ cc @elliottcable)的情况下工作,它也会阻止你更新签出的分支.请注意,如果更新不是快进,则可能需要传递-f(或使用`+ current:other`). (39认同)
  • 为什么要使用`git update-ref refs/heads/OtherBranch refs/heads/CurrentBranch`或`git push.CurrentBranch OtherBranch`当你可以使用更干净的(IMO)`git branch -f OtherBranch CurrentBranch`代替?(参见[我在git branch -f上的回答](http://stackoverflow.com/a/17604903/994153)) (15认同)
  • 您还可以使用`-m'some text'`参数来记录由`git reflog OtherBranch`命令显示ref更新的原因,例如"synched to CurrentBranch".记住你为什么以后这样做会很有用. (4认同)
  • 伙计,我希望这可以在没有多余的`refs/heads /`的情况下工作...... (2认同)
  • @ColinDBennett 可以为未来的读者节省一些时间:如果当前签出了 OtherBranch,则 `git Branch -f` 将不起作用,而 `git update-ref` 则可以。 (2认同)

Den*_*sov 20

您可以随时使用此命令与您的分支同步

$ git push . CurrentBranch:OtherBranch -f
Run Code Online (Sandbox Code Playgroud)

也没有-f它会替换这组命令

$ git checkout OtherBranch
$ git merge CurrentBranch
$ git checkout CurrentBranch
Run Code Online (Sandbox Code Playgroud)

当您不需要在CurrentBranch中提交所有文件时,它可能很有用,因此您无法切换到另一个分支.

  • 除非绝对必要,否则我不会包含`-f`选项。在我看来,如果没有它,它会很好地工作。 (2认同)