为什么Bash中带||的if字符串比较在git分支清理脚本中不生效?
问题原因
你的条件判断逻辑运算符使用错误,核心是混淆了「逻辑或||」和「逻辑与&&」的适用场景。
你写的"$branchname" != "origin/master" || "$branchname" != "origin/automation"本质是恒真表达式:只要origin/master和origin/automation是两个不同的分支名,不管branchname取什么值,总有一个子条件成立:
- 如果
branchname是origin/master:!= origin/automation子条件为真,整体判断为真 - 如果
branchname是origin/automation:!= origin/master子条件为真,整体判断为真 - 如果
branchname是其他值:两个子条件都为真,整体判断为真
这就是为什么两个排除规则完全没有生效,所有分支都会进入删除逻辑。
正确写法
你需要的逻辑是「仅当分支既不是origin/master,也不是origin/automation时,才执行删除」,也就是两个否定条件需要同时满足,应该用逻辑与&&连接。另外注意你原代码的for循环缺少了do关键字,在Jenkins Shell中运行也会触发语法错误,修正后的完整代码示例如下:
for branchname in `git branch -r --merged origin/master`; do if [[ "$branchname" != "origin/master" && "$branchname" != "origin/automation" ]]; then # 此处写你的删除分支逻辑 fi done
内容的提问来源于stack exchange,提问作者stillmaticone17
相关产品推荐
相关产品推荐

