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

