获取当前分支名称以在git命令中使用 [英] get current branch name for use in git command

查看:115
本文介绍了获取当前分支名称以在git命令中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我想使用当前分支名称在git命令中使用.例如

I sometimes want to use the current branch name to use in git commands. For example

git push origin feature/really-long-branch-name

是否有一个仅给出分支名称的git命令,以便我可以执行以下操作?

git push origin current_branch

git rev-parse --abbrev-ref HEAD ,但这在这种情况下确实有用.设置默认分支也无济于事,因为分支名称经常更改.更改 git push 的默认行为也不是我想要的,因为这仍然意味着我第一次 push 时必须键入完整的分支名称.

There is git rev-parse --abbrev-ref HEAD but that's exactly useful in this case. Setting a default branch isn't that helpful either since the branch name changes often. Changing the default behavior of git push isn't what I'm looking for either since it still means having to type in the full branch name the first time I push.

主持人,这个问题不是伪造的,因此请不要因为这个原因而关闭.请仔细阅读我问题的粗体部分.

Moderators, this question is not a dupe so please do not close for that reason. Please read the bolded part of my question carefully.

推荐答案

自2019年6月起,使用内置的-show-current 标志

尽管从2013年开始的答案经受了时间的考验,但Git早在2019年就学会了新的git-branch标志,这使得这变得容易得多.在提交 3710f60a80 时,git-branch学会了一个新的标志,无需显示当前分支用户自行解析分支列表或引用.您可以像这样调用它:

Since June 2019, Use Built-In --show-current Flag

While this answer from 2013 has stood the test of time, Git learned a new git-branch flag back in 2019 that makes this much easier. In commit 3710f60a80, git-branch learned a new flag for showing the current branch without requiring users to parse the list of branches or refs themselves. You can invoke it like so:

$ git branch --show-current
main

下面的其他方法仍然可以使用,但是现在它应该是Git发行版> = v2.22.0的首选解决方案.

The other methods below continue to work, but this should now be the go-to solution for Git release versions >= v2.22.0.

有很多方法可以获取当前分支的名称.最规范的方法是使用 git-symbolic-ref(1)读取HEAD的符号参考.例如,假设您位于 master 分支上:

There are a number of ways to get the name of the current branch. The most canonical is to read the symbolic ref for HEAD using git-symbolic-ref(1). For example, assuming you are on the master branch:

$ git symbolic-ref HEAD | sed 's!refs\/heads\/!!'
master

使用参考

无论如何解析,都可以通过调用外壳程序的命令替换.例如,在Bash中:

Using the Ref

However you parse it, you can use the symbolic name in another command by invoking your shell's command substitution. For example, in Bash:

$ git log -n1 $(git rev-parse --abbrev-ref HEAD)

如果选择的话,没有理由不能将这个技巧与push或其他命令一起使用.

There's no reason you couldn't use this trick with push or other commands, if you choose.

如果您只想将当前分支推送到具有相同名称的远程分支,并且不出于其他原因而解析引用,那么最好使用Git的 push.default.选项在此处

If you're only interested in pushing the current branch to a remote branch with the same name, and aren't parsing the refs for some other reason, then you'd be better off using Git's push.default option described here and here. For example:

git config push.default current

这篇关于获取当前分支名称以在git命令中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆