如果Shell脚本在任何阶段失败,Jenkins管道将退出

时间:2020-04-07 07:39:33

标签: shell jenkins jenkins-pipeline

我有jenkins管道作业,该作业在内部运行shell脚本。即使Shell脚本失败,作业也只会显示为已通过。

我的管道:

stage('Code Checkout') {
timestamps {
step([$class: 'WsCleanup'])
echo "check out======GIT =========== on ${env.gitlabBranch}"
checkout scm
}                                     
}
stage("build") {
sh 'sh script.sh'  
}
}
catch(err){
currentBuild.result = 'FAILURE'
emailExtraMsg = "Build Failure:"+ err.getMessage()
throw err
}
}
} 
LOG:
+ sh script.sh
$RELEASE_BRANCH is empty
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

1 个答案:

答案 0 :(得分:0)

看起来您的脚本返回的状态码为零。否则,它将引发异常,如sh step description中所述。问题可能是sh sctipt.sh的退出状态是最后执行的命令的退出状态,并且您的脚本可能在发生错误后执行了某些操作(例如,echo退出前已执行某些操作)。确保返回所有错误的最简单,最残酷的方法是在脚本顶部使用put set -e

您不需要任何catch即可具有此功能(我的意思是脚本错误失败),除非您想在发生错误的情况下进行一些额外的操作。但是,如果这样做,则应该将脚本执行放在try子句中:

stage("build") {
  try {
    sh 'sh script.sh'  
  }
  catch (err) {
    currentBuild.result = 'FAILURE'
    emailExtraMsg = "Build Failure:"+ err.getMessage()
    throw err
  }
}