天天看點

jenkins pipeline中擷取shell指令的标準輸出或者狀态

//擷取标準輸出

//第一種

result = sh returnStdout: true ,script: "<shell command>"
result = result.trim()      

//第二種

result = sh(script: "<shell command>", returnStdout: true).trim()      

//第三種

sh "<shell command> > commandResult"
result = readFile('commandResult').trim()      

//擷取執行狀态

result = sh returnStatus: true ,script: "<shell command>"
result = result.trim()      
result = sh(script: "<shell command>", returnStatus: true).trim()      
sh '<shell command>; echo $? > status'
def r = readFile('status').trim()      

//無需傳回值,僅執行shell指令

//最簡單的方式

sh '<shell command>'      

例如:

工作中需要擷取shell 指令的執行狀态,傳回0或者非0

groovy語句寫法為:

def exitValue = sh(script: "grep -i 'xxx' /etc/myfolder", returnStatus: true)
echo "return exitValue :${exitValue}"
if(exitValue != 0){
執行操作
}      

如果grep指令執行沒有報錯,正常情況下exitValue為0,報錯則為非0

需要注意的是當指令中存在重定向的時候,會出現傳回狀态異常,因為我們要傳回狀态,删除重定向(&>/dev/null)即可,比如:

def exitValue = sh(script: "grep -i 'xxx' /etc/myfolder &>/dev/null", returnStatus: true)
xxx不存在,正常邏輯是傳回非0,但是實際中傳回的是0 。可以了解為先執行指令然後指派操作,類似下面的動作:(個人了解)
sh "ls -l > commandResult"
result = readFile('commandResult').trim()      

groovy中存在另外一種解析shell腳本的方法,在jenkins pipeline中會使用會報異常,jenkins相關資料中也沒有看到此種用法,應該是不支援

groovy.lang.MissingPropertyException: No such property: rhel for class: groovy.lang.Binding      

寫法為:

def command = "git log"
def proc = command.execute()
proc.waitFor()
def status = proc.exitValue()      

相關資料:

https://stackoverflow.com/questions/36547680/how-to-do-i-get-the-output-of-a-shell-command-executed-using-into-a-variable-fro

https://issues.jenkins-ci.org/browse/JENKINS-26133

https://stackoverflow.com/questions/36956977/how-to-execute-a-command-in-a-jenkins-2-0-pipeline-job-and-then-return-the-stdou

---------------------

作者:liurizhou

來源:CSDN

原文:https://blog.csdn.net/liurizhou/article/details/86670092

版權聲明:本文為部落客原創文章,轉載請附上博文連結!

上一篇: jenkinsfile