Jenkins高階篇之Pipeline方法篇-Pipeline Basic Steps-2-方法fileExists、isUnix、pwd
阿新 • • 發佈:2019-01-04
繼續來學習pipeline basic steps裡面的方法,前面學習了資料夾相關的操作方法,這篇來學習幾個布林型別的返回值的方法。第一個是判斷一個檔案是否存在,第二個是判斷當前執行的環境是不是Linux還是windows。
1方法fileExists
這是判斷一個檔案是否存在,返回值是布林型別,true就表示檔案存在,false表示檔案不存在。這個我一般是用來驗證判斷,例如,我呼叫了一個請求,然後把請求回來的資料儲存為一個log或者json檔案。我在解析這個檔案之前,我會對這個檔案是否存在進行判斷,這個時候就可以使用fileExists,這個方法經常需要使用,你需要重點掌握。
程式碼
import hudson.model.*; println env.JOB_NAME println env.BUILD_NUMBER pipeline{ agent any stages{ stage("fileExists") { steps{ script { json_file = "${env.WORKSPACE}/testdata/test_json.json" if(fileExists(json_file) == true) { echo("json file is exists") }else { error("here haven't find json file") } } } } } }
關鍵日誌:
[Pipeline] } [Pipeline] // stage [Pipeline] withEnv [Pipeline] { [Pipeline] stage [Pipeline] { (fileExists) [Pipeline] script [Pipeline] { [Pipeline] fileExists [Pipeline] echo json file is exists [Pipeline] } [Pipeline] // script [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // withEnv [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline Finished: SUCCESS
2方法isUnix()
這個方法是判斷當前執行的Jenkins node環境是linux還是windows,如果返回是true表示是linux/mac系統,如果返回是false,表示當前jenkins job執行在windows的系統上。
pipeline stage 程式碼
import hudson.model.*; println env.JOB_NAME println env.BUILD_NUMBER pipeline{ agent any stages{ stage("fileExists") { steps{ script { if(isUnix() == true) { echo("this jenkins job running on a linux-like system") }else { error("the jenkins job running on a windows system") } } } } } }
我的jenkins master是linux,所以上面輸出的是
[Pipeline] stage
[Pipeline] { (fileExists)
[Pipeline] script
[Pipeline] {
[Pipeline] isUnix
[Pipeline] echo
this jenkins job running on a linux-like system
[Pipeline] }
[Pipeline] // script
3.方法pwd()
其實這個方法和linux下的shell命令pwd是一樣的。由於jenkins支援windows和linux,但是linux是pwd,windows上是dir。所以這個外掛就乾脆支援一個方法,統稱為pwd(),下面來試試linux上shell和外掛本身方法pwd()是否是一樣效果。
import hudson.model.*;
println env.JOB_NAME
println env.BUILD_NUMBER
pipeline{
agent any
stages{
stage("fileExists") {
steps{
script {
sh("pwd")
println "==========="
println pwd()
}
}
}
}
}
關鍵日誌
[pipeline_basic_steps] Running shell script
+ pwd
/var/lib/jenkins/workspace/pipeline_basic_steps
[Pipeline] echo
===========
[Pipeline] pwd
[Pipeline] echo
/var/lib/jenkins/workspace/pipeline_basic_steps
[Pipeline] }
[Pipeline] // script
這個方法pwd()在windows上也可以執行,只不過我沒有連線window的agent機器