Jenkins pipeline 流水线 执行 sh命令/shell脚本遇到 exit code 1。主要是部分工具有特殊问题,例如grep工具,在找得到指定字符串时候返回字符串,找不到就返回 1。这样就会导致Jenkins判断你1就退出了。
案例:
通过grep找运行中容器,判断docker运行中是否存在react-app,存在就停止。
sh 'test -n "$(docker ps | grep react-app)" && docker stop react-app'
报语法 不对
改:shell 脚本方案
# 脚本 名 stop.sh
#!/bin/sh
test -n "$(docker ps | grep react-app)" && docker stop react-app
test -n "$(docker container ls -a | grep react-app)" && docker rm react-app
test -z "$(docker network ls | grep testnet1)" && docker network create testnet1
然后 在 流水线里面 写 sh "./stop.sh"
如果 grep 有 相关容器就能跑 ,grep 为空 Jenkins执行报错:ERROR: script returned exit code 1
pipeline 是支持直接写脚本的,故此使用pipeline 内部脚本
pipeline {
agent any
stages {
stage('Example') {
steps {
script{
def code = sh (
script: "docker ps | grep react-app",
returnStatus: true // 注意得加上这个, 不然 sh 执行 不返回 状态 ,jenkins 执行到这里 如果 grep 还是 找不到 东西的话 又会报 Error : script returned exit code 1 的错
)
// code 为0 代表 grep 找到 了 react-app 相关 的 container
if (code==0){
echo "有在运行 react-app 相关容器, 先停止掉"
sh ("docker stop react-app")
}else{
echo "没有在运行 react-app 相关容器"
}
//其余部分继续写脚本
}
}
}
}
}
内部脚本再次执行就ok了
http://blog.xqlee.com/article/2412101126095585.html