[英]Determine if we checked out a branch or a tag with git
In a script, I would like to determine if a tag or a branch was checked out. 在脚本中,我想确定是否签出了标签或分支。
For now, I have: 现在,我有:
git describe --tags
It will show the tag name, but if we are on a branch, it will raise an error (with return status != 0
): 它将显示标记名称,但如果我们在分支上,则会引发错误(返回状态!=
0
):
fatal: No names found, cannot describe anything.
Can I rely on this behavior or is there a better/more official way to do so? 我可以依赖这种行为,还是有更好/更正式的方法呢?
Are there some cases that are not caught by this method that I should know? 是否有一些我不应该知道这种方法的案例?
You can use git symbolic-ref HEAD
to check if you are on a branch and get its name: 您可以使用
git symbolic-ref HEAD
来检查您是否在分支上并获取其名称:
> git checkout master
[....]
> git symbolic-ref HEAD
refs/heads/master
> echo $?
0
If you have checked out a tag you will get an error: 如果您签出了标签,则会收到错误消息:
> git checkout some_tag
[....]
> git symbolic-ref HEAD
fatal: ref HEAD is not a symbolic ref
> echo $?
128
(edit) better than what I had earlier: (编辑)比我之前更好:
if read what where huh; test "$what" = ref:
then echo On branch ${where#refs/heads/}
else echo "not on any branch; last checkout was:"
git reflog|sed '/checkout:/!d;q'
fi < "`git rev-parse --git-dir`"/HEAD
will tell you where your last checkout came from. 会告诉你最后一次结账的来源。
git log HEAD^! --oneline --decorate
will tell you all the symbolic names for your current commit. 将告诉您当前提交的所有符号名称。
git status (or git branch ) to know on which branch you are. git status (或git branch )来了解你所在的分支。 Note: you're always on a branch: the default branch is master .
注意:您始终在分支上:默认分支是master 。
Use git tag to know the list of tags on the current branch. 使用git标签知道当前分支上的标签列表。
Well after some testing around, it turns out git describe --tags
wasn't very reliable (in one case I had checked out a branch it did return something). 经过一些测试后,结果是
git describe --tags
不是很可靠(在一个案例中我检查了一个分支它确实返回了一些东西)。
I ended up using: 我最终使用:
git branch | grep '^*'
This will return the selected branch. 这将返回选定的分支。 In case I checked out a tag, this will return:
如果我签出了一个标签,这将返回:
* (no branch)
In my script I parse the string to check if it contains (no branch)
. 在我的脚本中,我解析字符串以检查它是否包含
(no branch)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.