从管道运行bash脚本总是挂起

时间:2020-02-28 19:34:22

标签: bash jenkins jenkins-pipeline

我创建了一个简单的管道来尝试运行脚本,然后我将对输出进行其他操作,但是根据詹金斯的说法,脚本(CheckTagsDates.sh)从未完成。如果我以SSH身份登录到Jenkins从属节点su(作为jenkins用户),导航到正确的工作空间文件夹,则我可以成功执行命令。

pipeline {
    agent {label 'agent'}
    stages {
        stage('Check for releases in past 24hr') {
            steps{
                sh 'chmod +x CheckTagsDates.sh'
                script {
                    def CheckTagsDates = sh(script: './CheckTagsDates.sh', returnStdout: true)
                    echo "${CheckTagsDates}"
                }
            }
        }
    }
}

这是CheckTagsDates.sh文件的内容

#!/bin/bash
while read line
do
        array[ $i ]="$line"
        (( i++ ))
done < <( curl -L -s 'https://registry.hub.docker.com/v2/repositories/library/centos/tags'|jq -r '."results"[] | "\(.name)&\(.last_updated)"')

for i in "${array[@]}"
do
        echo $i | cut -d '&' -f 1
        echo $i | cut -d '&' -f 2
done

这是控制台中脚本的输出

latest
2020-01-18T00:42:35.531397Z
centos8.1.1911
2020-01-18T00:42:33.410905Z
centos8
2020-01-18T00:42:29.783497Z
8.1.1911
2020-01-18T00:42:19.111164Z
8
2020-01-18T00:42:16.802842Z
centos7.7.1908
2019-11-12T00:42:46.131268Z
centos7
2019-11-12T00:42:41.619579Z
7.7.1908
2019-11-12T00:42:34.744446Z
7
2019-11-12T00:42:24.00689Z
centos7.6.1810
2019-07-02T14:42:37.943412Z

2 个答案:

答案 0 :(得分:1)

我在评论中告诉您的方式,我认为这是对回声指令进行字符串插值的错误使用。

Jenkins Pipeline使用与Groovy相同的规则进行字符串插值。 Groovy的String插值支持可能会使许多新来的人感到困惑。尽管Groovy支持使用单引号或双引号声明字符串,例如:

def singlyQuoted = 'Hello'
def doublyQuoted = "World"

仅后一个字符串将支持基于美元符号($)的字符串插值,例如:

def username = 'Jenkins'
echo 'Hello Mr. ${username}'
echo "I said, Hello Mr. ${username}"

会导致:

Hello Mr. ${username}
I said, Hello Mr. Jenkins

了解如何使用字符串插值对于使用Pipeline的一些更高级功能至关重要。

来源:https://jenkins.io/doc/book/pipeline/jenkinsfile/#string-interpolation

答案 1 :(得分:1)

作为这种情况的解决方法,我建议您在Groovy中而不是shell中解析json内容,并将脚本限制为仅检索json。

pipeline {
    agent {label 'agent'}
    stages {
        stage('Check for releases in past 24hr') {
            steps{
                script {
                    def TagsDates = sh(script: "curl -L -s 'https://registry.hub.docker.com/v2/repositories/library/centos/tags'", returnStdout: true).trim()
                    TagsDates = readJSON(text: TagsDates)
                    TagsDates.result.each {
                        echo("${it.name}")
                        echo("${it.last_updated}")
                    }
                }
            }
        }
    }
}