命令行脚本任务只是将提供的脚本作为 shell 脚本运行并检查其退出代码(非零表示错误)。问题是脚本的退出代码是最后一条语句的退出代码,默认情况下(除非给出-e 选项)无论错误如何,shell 都会继续运行,即:
失败的命令
步骤内容:
make -f nonexisting.mk
结果:
========================== Starting Command Output ===========================
/bin/bash --noprofile --norc /home/vsts/work/_temp/bc2da066-dd8a-432d-b15f-b9c2bf7a8e1f.sh
make: nonexisting.mk: No such file or directory
make: *** No rule to make target 'nonexisting.mk'. Stop.
##[error]Bash exited with code '2'.
Finishing: Command Line Script
make 命令返回退出代码 2 失败,任务被标记为失败。接下来的任务被跳过了。
失败的命令被下一条语句覆盖
步骤内容:
make -f nonexisting.mk
echo Do whatever else
结果:
========================== Starting Command Output ===========================
/bin/bash --noprofile --norc /home/vsts/work/_temp/0b2ceea2-2821-4866-83c7-5d37a832ffe5.sh
make: nonexisting.mk: No such file or directory
make: *** No rule to make target 'nonexisting.mk'. Stop.
Do whatever else
Finishing: Command Line Script
make 命令失败,但 shell 继续执行下一条语句 (echo),该语句成功,因此退出代码为 0,任务未检测到错误,管道成功执行。
使 shell 在出错时停止
步骤内容:
set -e
make -f nonexisting.mk
echo Do whatever else
结果:
========================== Starting Command Output ===========================
/bin/bash --noprofile --norc /home/vsts/work/_temp/7f6644d3-408c-4b5b-b4d3-1f544e8a80ec.sh
make: nonexisting.mk: No such file or directory
make: *** No rule to make target 'nonexisting.mk'. Stop.
##[error]Bash exited with code '2'.
Finishing: Command Line Script
shell 可以在遇到任何错误时退出;当make 命令失败时,脚本终止,echo 命令不执行,退出码为失败命令的退出码。任务再次检测到这并终止管道。
顺便说一句。这是 Jenkins 运行 shell 脚本的标准方式,默认传递 -e,因此它可以在 Jenkins 上运行而无需明确执行任何操作。
您可能需要查看您的任务脚本中是否有覆盖make 退出代码的命令。除非您希望脚本本身具有更复杂的逻辑,否则脚本中的 set -e 可能会起到作用。