9

从 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"
    }
}

现在,不管exit 1bash 脚本中的 s 是什么,groovy 脚本总是在获取返回码0rc发送Passed!邮件!

有什么建议为什么我无法在这个 Groovy 脚本中接收来自 bash 脚本的退出代码?

我需要使用返回码而不是退出码吗?

4

1 回答 1

12

你的 groovy 代码没问题。

我创建了一个新的管道作业来检查您的问题,但对其进行了一些更改。

我没有运行你的 shell 脚本,copy_file.sh而是创建了~/exit_with_1.sh脚本,它只以退出代码 1 退出。

这项工作有两个步骤:

  1. ~/exit_with_1.sh脚本的创建

  2. 运行脚本并检查存储在rc.

1在这个例子中,我得到了一个退出代码。如果您认为您的groovy <-> bash配置有问题,请考虑替换您的copy_file.sh内容,exit 1然后尝试打印结果(在发布电子邮件之前)。

我创建的詹金斯工作:

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}"
        }
    }
}
于 2018-08-30T13:39:03.067 回答