一.變量
1.直接定義
def x="abc"
2.從腳本執行結果賦值變量
branch = "/jen_script/return-branch.sh $group $job".execute().text
將結果通過逗號分隔,寫入數組里
branch = "one, two, three"
branch_list = branch[1..-2].tokenize(',')
3.引號
```python
def x="abc"
print '${x}' //輸出${x},不支持變量
print "${x}" //輸出abc,支持變量
print ''' //輸出${X},不支持變量
${X}
'''
print """ //輸出abc,支持變量
${X}
"""
二.流程判斷
1.判斷變量
if (x='abc') {
echo "abc"
} else (x='bcd') {
echo "bcd"
}
三.方法
1.定義方法並調用
//String是聲明這個變量應該類型是字符串,可以省略,類型則根據傳入類型而變
def createName(String givenName, String familyName){
return givenName + "" + familyName
}
//調用,可省略括號
createName(familyName = "Lee", givenName = "Bruce")
2.方法添加默認參數
def sayHello(String name = "zhangsan"){
print "hello ${name}"
}
//不傳參時括號不能省略了
sayHello()
3.閉包
//定義閉包
def codeBlock = {print "hello closure"}
//閉包還可以直接當成函數調用
codeBlock() //輸出hello closure
4.閉包作為參數傳遞給另一個方法
//定義閉包
def codeBlock = {print "hello closure"}
//定義一個方法,它接收一個閉包參數
def sayHello(closure) {
closure()
}
//在調用sayHello方法時可以這樣
sayHello(codeBlock)
//如果把閉包定義的語句去掉
sayHello( {print "hello closure"} )
//由於括號是非必需的,所以
sayHello {
print "hello closure"
}
//如果sayHello改成名字為pipeine就是,是不是很像jenkins的pipeline
pipeline {
print "hello closure"
}
5.閉包另類用法,定義一個stage方法
//定義方法,傳一個正常變量和一個閉包
def stage(String name, closue) {
print name
closue()
}
//在正常情況下,這樣使用stage函數
stage("stage name", {print "closure"})
//執行打印
//stage name
//closure
//可以用另一種寫法
stage("stage name") {
print "closure"
}
四.數組
1.定義數組,然后判斷是否在數組中。比如判斷two是否在one這個數組里,需要先定義字符串,后面切割。
pipeline {
agent any
environment {
one = "xxx,ddd,lll"
two = "ddd"
}
stages {
stage('pull') {
steps {
script {
list = one.split(',')
for ( i in list ) {
echo "$i"
echo "$two"
if (i == two) {
echo "ok two"
} else {
echo "no two"
}
}
}
}
}
}
}