You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins:Groovy变量与凭证TOKEN如何在单引号Shell脚本中调用?

Jenkins Pipeline 中同时调用凭证TOKEN与Groovy变量的解决方案

不需要依赖环境变量,以下两种优雅方式可以解决三重单引号无法访问Groovy变量、双引号转义$TOKEN冲突的问题:

方法1:字符串拼接(推荐)

将需要保留Shell原义的部分(含$TOKEN)用单引号包裹,Groovy变量直接通过字符串拼接插入,既避免$符号转义,又能正常引用Groovy变量:

def exampleUrl = "https://api.example.com/endpoint"
withCredentials([string(credentialsId: 'your-token-id', variable: 'TOKEN')]) {
    sh '''curl -H "Authorization: Bearer $TOKEN" ''' + exampleUrl
}

方法2:双引号转义Shell的$符号

用双引号包裹整个Shell脚本,将Shell需要识别的$TOKEN中的$转义为\$,Groovy会自动插值未转义的变量:

def exampleUrl = "https://api.example.com/endpoint"
withCredentials([string(credentialsId: 'your-token-id', variable: 'TOKEN')]) {
    sh "curl -H \"Authorization: Bearer \$TOKEN\" ${exampleUrl}"
}

方法3:多行字符串混合处理

复杂场景下用三重双引号包裹脚本,转义Shell的$,同时用${}明确指定Groovy变量:

def exampleUrl = "https://api.example.com/endpoint"
withCredentials([string(credentialsId: 'your-token-id', variable: 'TOKEN')]) {
    sh """
        curl -H "Authorization: Bearer \$TOKEN" ${exampleUrl}
        # 可添加更多Shell命令
    """
}

内容的提问来源于stack exchange,提问作者susgreg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 09:37:44