Search code examples
groovyjenkins-pipeline

"git submodule foreach" syntax error in Jenkins pipeline, but works on command line?


I can execute the following on a command line, where I just want to checkout a feature/* branch, and if the sub module does not have it, I want to checkout master.

$ git submodule foreach 'git checkout feature/test-new-scripts || git checkout master'

However, if I execute the same command in a Jenkins pipeline, I get a syntax error.

sh """
  git submodule foreach \\'git checkout feature/test-new-scripts || git checkout master\\'
"""

I get the following error

+ git submodule foreach "git checkout feature/test-new-scripts
Entering 'module1'
"git: 1: "git: Syntax error: Unterminated quoted string
fatal: run_command returned non-zero status for module1
.
+ git checkout master"
error: pathspec 'master"' did not match any file(s) known to git

I've tried the following syntax, where I just changed the single quotes ('...') in the command itself to double quotes ("..."), to no avail

sh """
  git submodule foreach \\"git checkout feature/test-new-scripts || git checkout master\\"
"""

What is the correct syntax do accomplish what I want to do?


Solution

  • As the error message indicates this is indeed an issue with Groovy string casting in the sh step method parameter. We can clean this up a bit to assist:

    sh(label: 'Git Submodule Checkout', script: "git submodule foreach 'git checkout feature/test-new-scripts || git checkout master'")
    

    It may also be possible to achieve this with the GitSCM class as well by the way.