//獲取標准輸出
//第一種
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
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!