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

Jenkins流水线Groovy内嵌Bash时$符号丢失问题求助

解决Jenkins流水线中密码含$符号在Bash中丢失的问题

问题原因

你用Groovy三重单引号(''')包裹Bash脚本时,Bash会把字符串里的$$解析为当前Shell的进程ID,导致密码中的第二个$被替换,最终密码内容丢失部分字符。另外你的代码里未将Groovy的password变量传递给Bash环境,直接使用$PASSWORD其实是调用未定义的Bash变量——这可能是你实际代码的疏漏,但核心问题在于特殊字符被Bash错误解析。

解决方案

方案1:用Groovy双引号三重字符串传递变量并包裹单引号

将Bash脚本改用Groovy三重双引号(""")包裹,Groovy会先替换变量内容再传给Bash;同时用单引号包裹变量,避免Bash解析内部特殊符号:

def password = params.get('PASSWORD')
stage('execute') {
    steps {
        script {
            println password // 输出正确的ppa$$worddd
            withCredentials([string(credentialsId: 'ID', variable: 'C_ID'),string(credentialsId: 'SE', variable: 'C_SE')]) {
                if (!starsValue.isEmpty()) {
                    sh """
                      cd Scripts
                      echo '$password' // 完整输出ppa$$worddd
                    """
                } 
            }
        }
    }
}

方案2:提前转义密码中的$符号

在Groovy中把密码里的$替换为\$,再传递给Bash,避免被解析:

def password = params.get('PASSWORD')
def escapedPassword = password.replace('$', '\\$')
stage('execute') {
    steps {
        script {
            println password
            withCredentials([string(credentialsId: 'ID', variable: 'C_ID'),string(credentialsId: 'SE', variable: 'C_SE')]) {
                if (!starsValue.isEmpty()) {
                    sh '''
                      cd Scripts
                      echo ''' + escapedPassword + '''
                    '''
                } 
            }
        }
    }
}

方案3:注入为环境变量后双引号引用

如果需要多次使用密码,可先导出为Jenkins环境变量,再在Bash中用双引号包裹(需提前转义特殊字符):

def password = params.get('PASSWORD')
stage('execute') {
    steps {
        script {
            println password
            env.PASSWORD = password.replace('$', '\\$')
            withCredentials([string(credentialsId: 'ID', variable: 'C_ID'),string(credentialsId: 'SE', variable: 'C_SE')]) {
                if (!starsValue.isEmpty()) {
                    sh '''
                      cd Scripts
                      echo "$PASSWORD"
                    '''
                } 
            }
        }
    }
}

关键说明

  • Groovy的'''是纯字符串,不会替换变量,内容直接交给Bash解析,特殊符号会被Bash处理;
  • Groovy的"""会先替换变量再传递给Bash,单引号包裹变量可阻止Bash解析内部特殊字符;
  • 密码中的$、!等符号在Bash中均有特殊含义,必须通过转义或单引号包裹避免被错误解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 06:14:53