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

Jenkins Pipeline中Shell脚本无法识别本地变量问题排查

Jenkins Pipeline Shell脚本变量解析错误解决方法

问题出在Groovy对双引号字符串的变量解析行为上:你用**双引号(""")**包裹shell脚本时,Groovy会尝试将其中的$DIFF识别为Pipeline的全局变量,但你的Pipeline中并没有定义DIFF属性,因此抛出MissingPropertyException`。

解决方法有两种:

方法1:改用单引号包裹shell脚本

单引号(`''')会让Groovy完全不解析内部变量,所有内容直接交给shell处理:

sshagent(credentials: ['myBBCreds']) {
  sh(label: "Commit updated translation files",
     script: '''
       DIFF=`git diff --name-only`
       if [ ! -z "$DIFF" ]; then
         echo "We have diffs: $DIFF"
         git add .
         git commit . -m "Jenkins ($environment - Zift123): Automated check-in of i18n files"            
       fi
     ''',
     returnStatus: true)
}

方法2:转义shell内部的变量

如果需要保留双引号(比如要引用Pipeline的$environment变量),对shell里的$DIFF添加反斜杠转义,告诉Groovy不要解析这个变量:

sshagent(credentials: ['myBBCreds']) {
  sh(label: "Commit updated translation files",
     script: """
       DIFF=`git diff --name-only`
       if [ ! -z "\$DIFF" ]; then
         echo "We have diffs: \$DIFF"
         git add .
         git commit . -m "Jenkins ($environment - Zift123): Automated check-in of i18n files"            
       fi
     """,
     returnStatus: true)
}

注:脚本中的$environment属于Pipeline变量,双引号下Groovy会正确解析它,转义仅针对shell自身的变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 07:38:12