You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash中分支名称正则匹配失败问题排查

Bash分支名正则匹配失败问题解决

你的脚本始终返回退出码1,核心原因是正则里的\d在Bash的正则规则里不生效,导致无法匹配分支名中的数字部分。

先看你的原代码:

#!/usr/bin/env bash
LC_ALL=C

local_branch="STORY-409-new-bash-file"

valid_branch_regex="(feature\/|bugfix\/|release\/|hotfix\/)?(PIB\-|STORY\-)(\d+)\-(.+)"
valid_branch_sample="[type]/[ticket-number]-description-with-hyphenated-string, i.e feature/STORY-584-do-something-here"

message="There is something wrong with your branch name. Branch names in this project must adhere to this contract: $valid_branch_sample. Your commit will be rejected. You should rename your branch to a valid name and try again."

if [[ ! $local_branch =~ $valid_branch_regex ]]

then
    echo "$message"
    exit 1
fi

exit 0

问题分析

Bash中[[ ... =~ ... ]]使用的是POSIX扩展正则表达式(ERE),而\d是Perl兼容正则(PCRE)里的语法,ERE并不支持用\d匹配数字,所以这部分完全无法匹配分支名里的409,导致整个正则匹配失败。

另外补充一点:正则里的\/和\-是多余的转义,因为/和-在ERE里不属于特殊字符,不需要转义,但这不是导致匹配失败的直接原因。

修复方案

把正则里的\d+替换成ERE支持的数字匹配写法,比如[0-9]+或者更规范的POSIX字符类[[:digit:]]+,同时可以去掉多余的转义符号。修改后的正则如下:

# 用[0-9]匹配数字
valid_branch_regex="(feature/|bugfix/|release/|hotfix/)?(PIB-|STORY-)([0-9]+)-(.+)"

或者:

# 用POSIX字符类,兼容性更好
valid_branch_regex="(feature/|bugfix/|release/|hotfix/)?(PIB-|STORY-)([[:digit:]]+)-(.+)"

修改后,分支名STORY-409-new-bash-file就能成功匹配,脚本会返回退出码0。

内容的提问来源于stack exchange,提问作者eloka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 00:20:56