【发布时间】:2019-07-04 10:43:49
【问题描述】:
我使用 Groovy 运行 Jenkins 管道作业。 Groovy 为每个步骤调用 bash 脚本。
当出现问题时,我想让整个工作失败。
对于 Groovy,我使用 returnStatus: true。
对于 Bash,我使用 set -e。
但是,如果 while 语句有错误,则带有 set -e 的 bash 脚本不会退出。根据“set”的 Linux 手册页,这实际上应该发生。
我想知道在那种情况下如何立即退出。
脚本:
[jenkins-user@jenkins ~]$ cat script.sh
#!/bin/bash
set -xe
FILE=commands.txt
echo "echos before while"
# Run the commands in the commands file
while read COMMAND
do
$COMMAND
done < $FILE
echo $?
echo "echos after faulty while"
假设“commands.txt”不存在。 运行脚本:
[jenkins-user@jenkins ~]$ sh script.sh
echos before while
script.sh: line 13: commands.txt: No such file or directory
1
echos after faulty while
[jenkins-user@jenkins ~]$ echo $?
0
虽然 while 语句返回退出代码 1,但脚本继续并成功结束,正如之后检查的那样,echo $?。
这就是我强制 Groovy 失败的方式,在使用 bash/python/etc 命令/脚本的步骤返回非零退出代码之后:
pipeline {
agent any
stages {
stage("A") {
steps {
script {
def rc = sh(script: "sh A.sh", returnStatus: true)
if (rc != 0) {
error "Failed, exiting now..."
}
}
}
}
}
}
第一个问题,当 while/if/etc 语句有错误时,如何使 SHELL 脚本失败?我知道我可以使用command || exit 1,但如果我在脚本中有几十个这样的语句,它似乎并不优雅。
第二个问题,我的 Groovy 错误处理是否正确?任何人都可以提出更好的活动方式吗?或者也许有一个 Jenkins 插件/官方方法可以做到这一点?
【问题讨论】:
-
有点晚了,但是你有没有解决这个问题,即自动检测到 bash 内置错误?感谢您让我知道 '-e' 没有涵盖 'while'。在使用它之前进行防御性编码的另一个原因,即
[[ -f $FILE ]]。
标签: linux bash shell jenkins groovy