[英]Is it possible to execute Jenkins jobs from Powershell or Bash or Groovy scripts?
[英]Capture exit code from bash scripts in jenkins groovy scripts
從Jenkins Groovy腳本執行bash腳本copy_file.sh
並嘗試根據bash腳本生成的退出代碼拍攝郵件。
copy_file.sh
:
#!/bin/bash
$dir_1=/some/path
$dir_2=/some/other/path
if [ ! -d $dir ]; then
echo "Directory $dir does not exist"
exit 1
else
cp $dir_2/file.txt $dir_1
if [ $? -eq 0 ]; then
echo "File copied successfully"
else
echo "File copy failed"
exit 1
fi
fi
groovy script
部分:
stage("Copy file") {
def rc = sh(script: "copy_file.sh", returnStatus: true)
echo "Return value of copy_file.sh: ${rc}"
if (rc != 0)
{
mail body: 'Failed!',
subject: 'File copy failed',
to: "xyz@abc.com"
System.exit(0)
}
else
{
mail body: 'Passed!',
subject: 'File copy successful',
to: "xyz@abc.com"
}
}
現在,無論bash腳本中的exit 1
是什么,groovy腳本總是在rc
獲得返回代碼0
並且射擊Passed!
郵件!
有什么建議我無法從這個Groovy腳本中的bash腳本接收退出代碼?
我是否需要使用退貨代碼退出退出代碼?
你的groovy代碼沒問題。
我創建了一個新的管道工作來檢查你的問題,但稍微改了一下。
而不是運行你的shell腳本的copy_file.sh
我創建~/exit_with_1.sh
腳本,只有為1的退出代碼退出。
這項工作有兩個步驟:
創建~/exit_with_1.sh
腳本
運行腳本並檢查存儲在rc
的退出代碼。
在這個例子中我得到1
作為退出代碼。 如果您認為groovy <-> bash
配置有問題,請考慮僅使用exit 1
替換copy_file.sh
內容,然后嘗試打印結果(在發布電子郵件之前)。
我創建的jenkins工作:
node('master') {
stage("Create script with exit code 1"){
// script path
SCRIPT_PATH = "~/exit_with_1.sh"
// create the script
sh "echo '# This script exits with 1' > ${SCRIPT_PATH}"
sh "echo 'exit 1' >> ${SCRIPT_PATH}"
// print it, just in case
sh "cat ${SCRIPT_PATH}"
// grant run permissions
sh "chmod +x ${SCRIPT_PATH}"
}
stage("Copy file") {
// script path
SCRIPT_PATH = "~/exit_with_1.sh"
// invoke script, and save exit code in "rc"
echo 'Running the exit script...'
rc = sh(script: "${SCRIPT_PATH}", returnStatus: true)
// check exit code
sh "echo \"exit code is : ${rc}\""
if (rc != 0)
{
sh "echo 'exit code is NOT zero'"
}
else
{
sh "echo 'exit code is zero'"
}
}
post {
always {
// remove script
sh "rm ${SCRIPT_PATH}"
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.