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
相关产品推荐
相关产品推荐

