[英]Jenkins Groovy script to execute shell commands
我正在使用一個 groovy 腳本來計算我的構建持續時間並將指標發布到托管石墨,從命令行將產生以下卷曲並產生預期效果:
echo {someMetricHere} | nc carbon.hostedgraphite.com 2003
但是,在我的 groovy 腳本中,生成指標的最后一步是運行以下命令:
"echo "+ metric +" | nc carbon.hostedgraphite.com 2003".execute()
它的回歸:
捕獲:java.io.IOException:無法運行程序“|”:錯誤=20,不是目錄 java.io.IOException:無法運行程序“|”:錯誤=20,不是 hudson8814765985646265134.run(hudson8814765985646265134. :27) 由:java.io.IOException: error=20, Not a directory ... 1 more
我假設該命令不理解“|” 命令的一部分,對如何修復此腳本以運行預期的 bash 有何建議? 我認為可以在工作區中創建一個 .sh 文件,但我不確定如何。
想要查看完整腳本的人的 Pastebin: https : //pastebin.com/izaXVucF
干杯:)
使用管|
試試這個代碼:
// this command line definitely works under linux:
def cmd = ['/bin/sh', '-c', 'echo "12345" | grep "23"']
// this one should work for you:
// def cmd = ['/bin/sh', '-c', 'echo "${metric}" | nc carbon.hostedgraphite.com 2003']
cmd.execute().with{
def output = new StringWriter()
def error = new StringWriter()
//wait for process ended and catch stderr and stdout.
it.waitForProcessOutput(output, error)
//check there is no error
println "error=$error"
println "output=$output"
println "code=${it.exitValue()}"
}
輸出:
error=
output=12345
code=0
我認為你所做的連接有問題。
此代碼應該工作:
"echo ${metric} | nc carbon.hostedgraphite.com 2003".execute()
實現此目的的更簡單方法是使用Jenkins Job DSL 。 它具有可從給定step
內發出的shell
命令。 例如:
// execute echo command
job('example-1') {
steps {
shell('echo Hello World!')
}
}
// read file from workspace
job('example-2') {
steps {
shell(readFileFromWorkspace('build.sh'))
}
}
您可以在此處找到參考。
如果必須將變量傳遞給 groovy 腳本,請使用${variableName}
。 雙引號不會像你想象的那樣解釋,每個編譯器都以一種奇怪的方式對待它。
在您的情況下,以下行應該有助於做您想做的事情:
sh "echo ${metric} | nc carbon.hostedgraphite.com 2003"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.