【问题标题】:Jenkinsfile: illegal string body character after dollar sign; solution: either escape a literal dollar sign "\$5" or bracket the value expressionJenkinsfile:美元符号后的非法字符串主体字符;解决方案:要么转义文字美元符号“\$5”,要么将值表达式括起来
【发布时间】:2019-08-22 13:28:27
【问题描述】:

我的管道在 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
            """
        }
    }

错误信息是:

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.

【问题讨论】:

    标签: jenkins groovy jenkins-pipeline


    【解决方案1】:

    将双引号 """ 替换为单引号 '''

    sh '''
        apt-get update 
        //...
    '''
    

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

    【讨论】:

    • 这是最简单的答案!
    • 这就是我需要的。谢谢
    • 因为简单并且正是我所需要的而被赞成。我有一个“shell”脚本,它做了一些 perl 和其他事情,并为 perl 和 bash 使用了变量。逃避一切是丑陋的,很高兴知道 Groovy 不需要它。
    【解决方案2】:

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

    改变:

    $(lsb_release -cs)
    

    到:

    \$(lsb_release -cs)
    

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

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

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

    【讨论】:

    • +1 表示 Groovy 编译器并不总是在源代码中报告错误的正确位置。
    • 同样,报告错误的行号是罪魁祸首(即 Groovy 中的错误)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 2015-08-21
    • 1970-01-01
    • 2018-01-16
    • 2021-04-25
    相关资源
    最近更新 更多