我使用Groovy运行Jenkins流水线作业,并为每个步骤调用Bash脚本。当其中任何一个步骤出现错误时,我希望整个作业都会失败。
对于Groovy,我使用"returnStatus: true"。
对于Bash,我使用"set -e"。
但是,如果Bash脚本中有一个while语句出现错误,使用"set -e"也无法退出。根据Linux手册页上的说明,实际上应该退出。我想知道如何在这种情况下立即退出。
以下是脚本内容:
假设“commands.txt”不存在。 运行脚本:
尽管
以下是我在使用bash/python等命令/脚本执行步骤后强制Groovy失败的方法:
对于Groovy,我使用"returnStatus: true"。
对于Bash,我使用"set -e"。
但是,如果Bash脚本中有一个while语句出现错误,使用"set -e"也无法退出。根据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 $?
进行检查。以下是我在使用bash/python等命令/脚本执行步骤后强制Groovy失败的方法:
pipeline {
agent any
stages {
stage("A") {
steps {
script {
def rc = sh(script: "sh A.sh", returnStatus: true)
if (rc != 0) {
error "Failed, exiting now..."
}
}
}
}
}
}
第一个问题,我怎样才能使SHELL脚本在while/if等语句发生错误时失败?我知道可以使用command || exit 1
,但如果脚本中有数十个这样的语句,这种方法似乎不够优雅。
第二个问题,我的Groovy错误处理是否正确?有人能提出更好的方式吗?或者也许有Jenkins插件/官方方法来完成这个任务?
[[ -f $FILE ]]
。 - akauppi