Git:将分支设置为当前参考

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7580542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 11:57:13  来源:igfitidea点击:

Git: set branch to current ref

git

提问by Patrick B.

Due to the use of submodules in my projects I'm finding myself often on "(no branch)". As I'm also adding code to those submodules I'm committing in there. When I then want to push those submodules I need to be on a branch of course. Hence my question:

由于在我的项目中使用子模块,我发现自己经常处于“(无分支)”状态。因为我也在向那些我在那里提交的子模块添加代码。当我想要推送这些子模块时,我当然需要在一个分支上。因此我的问题是:

Is there a way/shortcut in git (command line) to set a local branch to the current commit/HEAD without the detour of

git(命令行)中是否有一种方法/快捷方式可以将本地分支设置为当前提交/HEAD,而无需绕道

git checkout the_branch
git reset --hard <previous commit-ish>

To be more precise, my real problem with the above "detour" is that I'm temporarily leaving the original HEAD with the checkout-command. That can be avoid with the git branch -fcommand (thanks to CharlesB).

更准确地说,我对上述“绕道”的真正问题是,我暂时使用 checkout-command 离开了原始 HEAD。这可以通过git branch -f命令避免(感谢 CharlesB)。

回答by CharlesB

Checkout the branch with -B: this will reset the branch to HEAD, which is the current ref.

使用以下命令检查分支-B:这会将分支重置为 HEAD,也就是当前的引用。

git checkout -B <branch> 

From the docs:

文档

If -B is given, is created if it doesn't exist; otherwise, it is reset. This is the transactional equivalent of

$ git branch -f <branch> [<start point>]
$ git checkout <branch>

that is to say, the branch is not reset/created unless "git checkout" is successful.

如果给出 -B,则如果不存在则创建;否则,它被重置。这是交易等价物

$ git branch -f <branch> [<start point>]
$ git checkout <branch>

也就是说,除非“git checkout”成功,否则不会重置/创建分支。

回答by knittl

git checkout -B the_branch HEAD

This will checkout the_branchat commit HEAD, even if the_branchpointed somewhere else before. It was added in one of the last few git releases, so you might not have it available. An alternate route would be git branch -D the_branch && git checkout -b the_branch

这将the_branch在提交 HEAD时签出,即使the_branch之前指向其他地方。它是在最近几个 git 版本之一中添加的,因此您可能无法使用它。替代路线是git branch -D the_branch && git checkout -b the_branch