加载 groovy 脚本时出现语法问题

syntax issue while loading groovy script

在声明性管道中加载 groovy 脚本时,我不断遇到语法问题:

[Pipeline] script
[Pipeline] {
[Pipeline] container
[Pipeline] {
[Pipeline] pwd
[Pipeline] sh
11:29:01  + /home/jenkins/workspace/CTO/CSF/Analytics/CSF-CJUP-TEST-CI/Jenkins/interactive.groovy
11:29:01  /home/jenkins/workspace/CTO/CSF/Analytics/CSF-CJUP-TEST-CI/Jenkins/interactive.groovy: line 2: syntax error near unexpected token `('
11:29:01  /home/jenkins/workspace/CTO/CSF/Analytics/CSF-CJUP-TEST-CI/Jenkins/interactive.groovy: line 2: `def exampleMethod() {'
[Pipeline] }
[Pipeline] // container
[Pipeline] }

相关代码:

steps {
    container('tools') {
        if ( env.RELEASE == 'true' ) {
            sh "${pwd()}/Jenkins/interactive.groovy"
            def interactive = load "${pwd()}/Jenkins/interactive.groovy"
            interactive.exampleMethod()
        }
    }
}

interactive.groovy

def exampleMethod() {
   println("exampleMethod")
}

def otherExampleMethod() {
    println("otherExampleMethod")
}
return this

问题出在这一行:

sh "${pwd()}/Jenkins/interactive.groovy"

由于您没有在 groovy 文件中使用 shebang(类似于第一行中的 #!/usr/bin/groovy),shell 试图将其解释为 bash脚本,导致错误。

只需删除此行并使用下面的 load 步骤。