捕获退出代码 bash 脚本B. jenkins groovy 脚本

场景执行 bash
copy_file.sh

来自脚本 Jenkins Groovy 并尝试根据脚本生成的输出代码删除邮件 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"
}
}


现在,无论如何
exit 1

s 在情景中 bash, 设想 groovy 始终获取返回码
0

在情景中
rc

并删除字母
Passed!

!

有建议为什么我无法从脚本中获取退出代码 bash 在这个脚本中 Groovy?

是否需要使用返回码而不是输出代码?
已邀请:

二哥

赞同来自:

你的代码 groovy - OK.

我创建了一个新的传送带任务来检查你的问题,但有点改变它。

而不是推出你的脚本 shell
copy_file.sh

我创建了脚本
~/exit_with_1.sh

, 它只与退出代码一起使用 1.

任务包括 2 脚步:

创建脚本
~/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}"
}
}
}

要回复问题请先登录注册