将Groovy变量传递给Shell脚本

14

我刚开始学习Groovy。我想在svn复制命令中传递svnSourcePath和svnDestPath到shell脚本。但是URL没有被渲染。

node {
 stage 'Copy Svn code'

def svnSourcePath = "${svnBaseURL}${svnAppCode}${svnEnvDev}${SVN_DEV_PACKAGE}"
def svnDestPath = "${svnBaseURL}${svnAppCode}${svnEnvTest}${SVN_DEV_PACKAGE}"

print "DEBUG: svnSourcePath = ${svnSourcePath}"
print "DEBUG: svnDestPath = ${svnDestPath}"

withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: crendentialsIdSVN, passwordVariable: 'SVN_PWD', usernameVariable: 'SVN_USER']]) {
    sh '''  
    svn copy $svnSourcePath $svnDestPath -m 'promote dev to test' --username $SVN_USER --password $SVN_PWD '''
}  
}

输出

+ svn copy -m 'promote dev to test' --username techuser --password 'xxxyyy' 
     svn: E205001: Try 'svn help' for more info
     svn: E205001: Not enough arguments provided

1
给那位给这个问题投了反对票的人 - 没有解释就投反对票有什么意义呢? - Amos Bordowitz
https://dev59.com/tFkS5IYBdhLWcg3wXFg9#66637408 - Shubham Jain
7个回答

14

在变量周围添加单引号和加号运算符('+ variable +')。现在它可以正常工作了。

svn copy '''+svnSourcePath+' '+svnDestPath+''' -m 'promote dev to test' --username $SVN_USER --password $SVN_PWD '''

6

+1对Selvam的回答

以下是我的使用情况和参数插件

字符串参数名称:pipelineParameter

默认值:4

node {
  stage('test') {
        withCredentials([[...]]) {
          def pipelineValue = "${pipelineParameter}"  //declare the parameter in groovy and use it in shellscript
          sh '''
             echo '''+pipelineValue+' abcd''''
             '''
        }
}}

以上代码输出4个abcd。

5
你可以使用""" content $var """。在这里文件中,"""允许字符串插值;而'''则不允许。

1
如果需要bash脚本,您需要像下面这样做:
在全局或本地(函数)级别设置此变量,从而可以使这些变量在sh脚本中可访问:
def stageOneWorkSpace = "/path/test1"
def stageTwoWorkSpace = "/path/test2"

在 shell 脚本中,可以像下面这样调用它们:
sh '''
echo ''' +stageOneWorkSpace+ '''
echo ''' +stageTwoWorkSpace+ '''
cd ''' +stageOneWorkSpace+  '''
rm -r ''' +stageOneWorkSpace+ '''/AllResults
mkdir -p AllResults
mkdir -p AllResults/test1
mkdir -p AllResults/test2
cp -r ''' +stageOneWorkSpace+'''/qa/results/* ''' +stageOneWorkSpace+'''/AllResults/test1
cp -r ''' +stageTwoWorkSpace+'''/qa/results/* ''' +stageOneWorkSpace+'''/AllResults/test2
'''

0

只有一次双引号也可以工作

stage('test') {  
  steps {  
    script {  
      for(job in env.JOB_NAMES.split(',')) {  
        println(job);  
        sh "bash jenkins/script.sh $job"  
        sh "echo $job"  
      }  
    }//end of script  
  }//end of steps  
}//end of stage test

0

当我在寻找一种在sh命令中插入变量值的方法时,我遇到了这个问题。

单引号'string' 和三个单引号 '''string'''字符串都不支持插值。

根据Groovy文档:

单引号字符串是普通的java.lang.String类型,不支持插值。

三个单引号字符串也是普通的java.lang.String类型,不支持插值。

因此,在groovy中使用嵌入式字符串值(GString),必须使用双引号,即使它在一个单引号字符串中也会被计算。

    sh "git commit -m  'Build-Server: ${server}', during main build."

-1
def my_var = "hai"
sh (
    script:  "echo " + my_var,
    returnStdout: true
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接