从jenkins groovy脚本中的bash脚本捕获退出代码

Foo*_*aut 4 bash exit jenkins jenkins-groovy jenkins-pipeline

copy_file.sh从Jenkins Groovy脚本执行bash脚本,并尝试根据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
Run Code Online (Sandbox Code Playgroud)

的部分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"
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,无论的exit 1在bash脚本S,Groovy脚本总是得到返回代码0rc,投篮命中率Passed!邮件!

为什么我无法在此Groovy脚本中从bash脚本接收退出代码有任何建议?

我是否需要使用return代码,而不是退出代码?

nat*_*sun 5

您的常规代码还可以。

我创建了一个新的管道作业来检查您的问题,但是做了一些改动。

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

作业有2个步骤:

  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}"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)