惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
博客园 - 司徒正美
Last Week in AI
Last Week in AI
Recent Announcements
Recent Announcements
Y
Y Combinator Blog
博客园 - 聂微东
M
MIT News - Artificial intelligence
博客园_首页
Jina AI
Jina AI
博客园 - 叶小钗
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
J
Java Code Geeks
F
Fortinet All Blogs
aimingoo的专栏
aimingoo的专栏
小众软件
小众软件
Vercel News
Vercel News
The Cloudflare Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
云风的 BLOG
云风的 BLOG
N
Netflix TechBlog - Medium
B
Blog
Google DeepMind News
Google DeepMind News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

二丫讲梵

学习周刊-总第258期-2026年第15周 学习周刊-总第257期-2026年第14周 学习周刊-总第256期-2026年第13周 学习周刊-总第255期-2026年第12周 学习周刊-总第254期-2026年第11周 学习周刊-总第253期-2026年第10周 临时插播一条羊毛,免费领取450元大模型API代金券 学习周刊-总第252期-2026年第09周 学习周刊-总第251期-2026年第08周 学习周刊-总第250期-2026年第07周 学习周刊-总第249期-2026年第06周 诚邀评论,聊聊你所知欲知的我 学习周刊-总第248期-2026年第05周 我的QQ动态之2015年 我的QQ动态之2014年 我的QQ动态之2013年 我的QQ动态之2012年 我的QQ动态-2010-2011年 我的QQ动态-创栏小叙 学习周刊-总第247期-2026年第04周 Nexus社区版权益阉割--一文告诉你有哪些版本可以选择 学习周刊-总第246期-2026年第03周 学习周刊-总第245期-2026年第02周 学习周刊-总第244期-2026年第01周 学习周刊-总第243期-2025年第52周 学习周刊-总第242期-2025年第51周 开源项目ZenOps:带你领略禅意运维 学习周刊-总第241期-2025年第50周 用京东金融,享负债人生 学习周刊-总第240期-2025年第49周
Jenkins-Groovy中Switch的高阶用法
二丫讲梵 · 2023-09-08 · via 二丫讲梵

在流水线的构建过程中,免不了会有逻辑判断的地方,通常我们可以使用 when,if 来编写判断的语句,但是当需要判断的分支大于两个的时候,就不再推荐使用如上两种方式了。

简言之,如果是布尔性质的判断,则推荐使用 when 和 if 来实现自己的需求,当判断的分支较多的时候,则推荐使用 switch 来解决这个场景的需求。

switch 的基本书写语法如下:

script {
    switch (PARAM) {
        case "a":
            println ("this is a")
            break
        case "b":
            println ("this is b")
            break
        default:
            println ("this is default")
            break
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13

因为 switch 属于 groovy 语法中的内容,所以需要在 script 关键字包裹之下。

上边是一个比较常规的写法,还有一些变种的写法,这里也做一下介绍。

多个分支有相同的处理逻辑,这个时候,可以讲这些分支进行合并,有如下两种方式:

script {
    switch(PARAM) {
        case "a":
            println("this is a")
            break
        // 第一种
        case "b":
        case "c":
            println("this is the first")
            break
        // 第二种
        case ["d", "e", 'inList']:
            println("this is second")
            break
        default:
            println("this is default")
            break
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

在一些判断逻辑场景中,合理适当运用 switch,能够让你的代码看起来更加简洁,专业,优雅。

快用起来吧。