从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: "[email protected]"
System.exit(0)
}
else
{
mail body: 'Passed!',
subject: 'File copy successful',
to: "[email protected]"
}
}
现在,无论bash脚本中的exit 1
s如何,groovy脚本总是在0
获取返回代码rc
并拍摄Passed!
邮件!
有什么建议我无法从这个Groovy脚本中的bash脚本接收退出代码?
我是否需要在退出代码中使用退货代码?
你的groovy代码没问题。
我创建了一个新的管道工作来检查你的问题,但稍微改了一下。
我没有运行你的shell脚本copy_file.sh
,而是创建了~/exit_with_1.sh
脚本,只退出退出代码为1。
这项工作有两个步骤:
~/exit_with_1.sh
脚本rc
中的退出代码。在这个例子中,我将1
作为退出代码。如果您认为groovy <-> bash
配置有问题,请考虑仅使用copy_file.sh
替换您的exit 1
内容,然后尝试打印结果(在发布电子邮件之前)。
我创建的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}"
}
}
}