5

Jenkins-Groovy中Switch的高阶用法

 11 months ago
source link: https://wiki.eryajf.net/pages/44a06c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Jenkins-Groovy中Switch的高阶用法

文章发布较早,内容可能过时,阅读注意甄别。

在流水线的构建过程中,免不了会有逻辑判断的地方,通常我们可以使用 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,能够让你的代码看起来更加简洁,专业,优雅。

快用起来吧。

1694100590964.jpg
微信
支付宝
上次更新: 2023/09/07, 23:31:16

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK