Jenkinsfile:美元符号后的非法字符串体字符;解决方案:要么转义文字美元符号“ \ $ 5”,要么将值表达式括起来

Den*_*nis 3 jenkins jenkins-pipeline

我的管道在Jenkinsfile的sh“”“元素处失败。知道哪里出错了吗?

    stage('Install dependencies') {
                when { expression { return params.dependencies } } }
        steps {
            sh """
              apt-get update
                            apt-get install -y openssh-server net-tools inetutils-ping python-pip rubygems
                            apt-get install -y \
                                apt-transport-https \
                                ca-certificates \
                                curl \
                                gnupg2 \
                                software-properties-common

                            curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add -

                            add-apt-repository \
                               "deb [arch=amd64] https://download.docker.com/linux/debian \
                               $(lsb_release -cs) \
                               stable"

                            apt-get update
                            apt-get install -y docker-ce docker-ce-cli containerd.io
                            curl -L "https://github.com/docker/compose/releases/download/1.23.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
                            chmod +x /usr/local/bin/docker-compose
                            gem install serverspec pygmy
            """
        }
    }
Run Code Online (Sandbox Code Playgroud)

错误消息是:

WorkflowScript: 35: illegal string body character after dollar sign;
solution: either escape a literal dollar sign "\$5" or bracket the value expression "${5}" @ line 35, column 17.
Run Code Online (Sandbox Code Playgroud)

Mat*_*ice 24

如果你想使用 groovy 的字符串插值,你可以保留双引号,但你必须在你的子 shell 表达式中转义美元符号,因为 groovy 不知道如何处理美元符号后面的圆括号:

改变:

$(lsb_release -cs)
Run Code Online (Sandbox Code Playgroud)

到:

\$(lsb_release -cs)
Run Code Online (Sandbox Code Playgroud)

我注意到错误消息指示错误的行。就我而言:

sh """
   echo "message: ${env.MESSAGE}" # <-- error message points here
   pwd
   echo "ls: $(ls)" <-- this line has the problem
"""
Run Code Online (Sandbox Code Playgroud)

在错误消息指示的行之后查找第一个美元符号。

  • +1 指出 Groovy 编译器并不总是报告源中错误的正确位置。 (3认同)

Szy*_*iak 6

"""用单引号替换双引号'''

sh '''
    apt-get update 
    //...
'''
Run Code Online (Sandbox Code Playgroud)

每当Groovy $在双引号中看到它时,都会将此字符串视为GString并进行字符串插值。但是,在您的情况下,$在插值上下文中不使用字符,它会失败。另外,您可以转义,\$但是切换到单引号字符串更有意义。