我使用以下命令来查找是否存在一个名为 branch-name
的本地 git 分支。这样做正确吗?有更好的方法吗?
请注意,我是在脚本内执行此操作。因此,如果可能的话,我想使用plumbing命令。
git show-ref --verify --quiet refs/heads/<branch-name>
# $? == 0 means local branch with <branch-name> exists.
我使用以下命令来查找是否存在一个名为 branch-name
的本地 git 分支。这样做正确吗?有更好的方法吗?
请注意,我是在脚本内执行此操作。因此,如果可能的话,我想使用plumbing命令。
git show-ref --verify --quiet refs/heads/<branch-name>
# $? == 0 means local branch with <branch-name> exists.
当我在搜索引擎上搜索'git检查分支是否存在'时,这个页面是我看到的第一个。
我得到了我想要的信息,但我想提供一个更新的答案,因为原始帖子是从2011年发布的。
git rev-parse --verify <branch_name>
这基本上与被接受的答案相同,但您不需要键入“refs/heads/”
因此,在shell脚本中,这将是:
if [ `git rev-parse --verify main 2>/dev/null` ]
then
...
fi
git rev-parse --verify
命令只会告诉你一个对象是否存在于代码库中(例如,对于任何能够在代码库中找到的对象,它都会返回0)。但是它并不会告诉你这个对象是否是一个分支。 - tavnabfatal: Needed a single revision
。 - HDJEMAI[
... ]
。只需使用 if git rev-parse --verify main >/dev/null 2>&1 ; then ...
。它使用命令返回的成功/失败状态。(如注释所述,它对分支和标签都返回 true。) - Keith Thompson<branch-name>
。<branch-name>
的好处很明显。顺便说一下,我正在使用这个在一个fabric脚本中。我会记得引用这个变量的。 - Manoj Govindan我建议使用git show-ref --quiet refs/heads/$name
。
--quiet
表示没有输出,这很好,因为你可以清楚地检查退出状态。
refs/heads/$name
限制为本地分支并匹配完整名称(否则dev
将匹配develop
)
在脚本中的用法:
if git show-ref --quiet refs/heads/develop; then
echo develop branch exists
fi
就快完成了。
只需省略--verify
和--quiet
,如果分支存在,则会返回哈希值,否则返回空值。
将其分配给一个变量并检查是否为空字符串。
exists=`git show-ref refs/heads/<branch-name>`
if [ -n "$exists" ]; then
echo '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-branch
。$ git show-branch --list
[master] test
* [testbranch] test
$ git show-branch testbranch
[testbranch] test
$ echo $?
0
$ git show-branch nonexistantbranch
fatal: bad sha1 reference nonexistantbranch
$ echo $?
128
因此,$? == 0
表示该分支存在,您无需深入了解refs/heads/的内部工作。只要不向show-branch
传递-r
,它就只会在本地分支上运行。git show-branch
是一个_瓷器_命令。正如我在问题中所说的,如果有等效的管道命令,我宁愿不在脚本中使用瓷器命令。请参见http://www.kernel.org/pub/software/scm/git/docs/。 - Manoj Govindangit show-branch refs/heads/[branch]
或 git show-branch refs/remotes/origin/[branch]
。 - twasbrilliggit branch -l <branch-name>
如果分支存在,则返回分支名,如果不存在则返回空
git_checkout_main() { main_branch=$(git branch -l main) if [ -z "${main_branch}" ]; then git checkout master else git checkout main fi }
- Vietgit rev-parse --verify <branch>
if %ERRORLEVEL% == 0 (
echo "Yes"
) else (
echo "No"
)
git rev-parse [<options>] <args>…
请参见https://git-scm.com/docs/git-rev-parse,您可以在其中找到参数集和函数。
git rev-parse --verify <branch-name>
我们称其为git is_localbranch
(您需要在.gitconfig
中添加别名)。
用法:
$ git is_localbranch BRANCH
来源:
git branch | grep -w $1 > /dev/null
if [ $? = 0 ]
then
echo "branch exists"
fi
git branch | grep -w <branch-name>
。虽然这是一个表面命令,但我认为未来不太可能对这种用法进行重大更改,因此这段代码仍然可用。 - UncleZeivgit rev-parse --verify <branch_name>
命令可以验证分支名称,也可以验证标签和提交哈希等其他引用。因此,如果你只对分支感兴趣,它可能不太适合你,因为它会返回误报。需要注意的是,翻译过程中不能改变原文意思。 - Paul S.git rev-parse --verify <branch-name>
(即branch-name
而不是branch_name
)? - Gautam