我正在使用下面的命令来查找在我的存储库中是否存在一个带有branch-name的本地git分支。这对吗?有没有更好的办法?
请注意,我是在脚本中执行此操作的。因此,如果可能的话,我希望使用管道命令。
git show-ref --verify --quiet refs/heads/<branch-name>
# $? == 0 means local branch with <branch-name> exists.
我正在使用下面的命令来查找在我的存储库中是否存在一个带有branch-name的本地git分支。这对吗?有没有更好的办法?
请注意,我是在脚本中执行此操作的。因此,如果可能的话,我希望使用管道命令。
git show-ref --verify --quiet refs/heads/<branch-name>
# $? == 0 means local branch with <branch-name> exists.
当前回答
我对最初问题“更新”的“建议编辑”的审查结果是“它应该作为评论或答案写出来”,所以我把它贴在这里:
提出的另一种方法不仅将验证分支,还将验证任何具有@jhuynh这样名称的引用。
git rev-parse --verify <reference-name>
# $? == 0 means reference with <reference-name> exists.
关于初始问题的“更新”问题解释如下:
让我们假设并检查master。000'只是一个标记,这样的本地分支不存在,grep返回一个标记条目。如果引用存在,仍然rev-parse将返回0,即使这样的本地分支不存在。正如@paul-s所提到的,这是一个错误的匹配
$ git show-ref |grep master.000
f0686b8c16401be87e72f9466083d29295b86f4a refs/tags/master.000
$ git rev-parse --verify master.000
f0686b8c16401be87e72f9466083d29295b86f4a
$ echo $?
0
其他回答
如果您能设法包括grep。
git branch | grep -q <branch>
我推荐git show-ref——quiet refs/heads/$name。
——quiet意味着没有输出,这很好,因为这样你就可以干净地检查退出状态。 引用/heads/$name限制到本地分支并匹配完整名称(否则dev将匹配develop)
在脚本中的用法:
if git show-ref --quiet refs/heads/develop; then
echo develop branch exists
fi
在脚本中使用:
git show-ref -q --heads <branch-name>
当且仅当<branch-name>存在时,该函数将退出0 作为一个地方分支机构。
例子:
if git show-ref -q --heads <branch-name>; then
echo 'Branch exists'
fi
git show-ref和git rev-parse都不能在我的情况下工作。
$ git --version
git version 2.21.0
$ git show-branch --list
* [master] mybranch commit
$ BRANCH_NAME=mybranch
$ git rev-parse --verify $BRANCH_NAME
fatal: Needed a single revision
$ git show-ref refs/heads/$BRANCH_NAME
<no otput>
$ [ $? == 0 ] && echo "$BRANCH_NAME exists" || echo "$BRANCH_NAME not exists"
mybranch not exists
最后得到了这个
$ BRANCH_NAME=mybranch
$ SHOW_ALL=`git show-branch --all | grep -w $BRANCH_NAME`
$ [ $? == 0 ] && echo "$BRANCH_NAME exists" || echo "$BRANCH_NAME not exists"
mybranch exists
您也可以使用脚本文件
#!/bin/sh
BRANCH_NAME=mybranch
if grep -Fqe $BRANCH_NAME << EOF
`git show-branch --all`
EOF
then
echo "$BRANCH_NAME exists"
else
echo "$BRANCH_NAME not exists"
fi
对于在脚本中使用,我建议使用以下命令:
git ls-remote --heads <repo_url> "<branch_name>" | wc -l
注意,<repo_url>可以只是一个“。”来指定本地回收(如果您在其目录结构中)、本地回收的路径或远程回收的地址。
如果<branch_name>不存在,则该命令返回0,如果存在则返回1。