[英]Capture exit code from bash scripts in jenkins groovy scripts
Executing a bash script copy_file.sh
from Jenkins Groovy script and trying to shoot mail depending upon the exit code generated form the bash script. 从Jenkins Groovy脚本执行bash脚本copy_file.sh
并尝试根据bash脚本生成的退出代码拍摄邮件。
copy_file.sh
: 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
Portion of the groovy script
: 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"
}
}
Now, irrespective of the exit 1
s in bash script, groovy script is always getting return code 0
in rc
and shooting Passed!
现在,无论bash脚本中的exit 1
是什么,groovy脚本总是在rc
获得返回代码0
并且射击Passed!
mails! 邮件!
Any suggestions why I can not receive the exit code from bash script in this Groovy script? 有什么建议我无法从这个Groovy脚本中的bash脚本接收退出代码?
DO I NEED TO USE RETURN CODE INSTEAD OF EXIT CODE? 我是否需要使用退货代码退出退出代码?
Your groovy code is OK. 你的groovy代码没问题。
I created a new pipeline job to check your problem, but altered it a bit. 我创建了一个新的管道工作来检查你的问题,但稍微改了一下。
Instead of running your shell script copy_file.sh
I created ~/exit_with_1.sh
script, that only exits with an exit code of 1. 而不是运行你的shell脚本的copy_file.sh
我创建~/exit_with_1.sh
脚本,只有为1的退出代码退出。
The job has 2 steps: 这项工作有两个步骤:
Creation of ~/exit_with_1.sh
script 创建~/exit_with_1.sh
脚本
Run the script and check the exit code that stored in rc
. 运行脚本并检查存储在rc
的退出代码。
I got 1
as an exit code in this example. 在这个例子中我得到1
作为退出代码。 If you think something wrong with your groovy <-> bash
configuration, consider replace your copy_file.sh
content with only exit 1
then try to print the result (before posting the emails). 如果您认为groovy <-> bash
配置有问题,请考虑仅使用exit 1
替换copy_file.sh
内容,然后尝试打印结果(在发布电子邮件之前)。
The jenkins job I created: 我创建的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.