Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error while using backslash in Jenkinsfile

I try to make simple pipeline on Jenkins to remove files from few directories time to time. I decided not to create python script with Jenkinsfile as new project, instead of it I try to define new pipeline script in Jenkins job.

pipeline {

  agent any

  stages {
    stage('Check virtualenv') {
      steps {
          sh """
            rm -r /mnt/x/some/directory/Problem\ 1.0/path
          """
      }
    }
  }
}

And I got an error WorkflowScript: 4: unexpected char: '\'. How can I use path with whitespace on it without using backslash? Any other ideas how define path?

like image 311
Alex Avatar asked Mar 08 '18 16:03

Alex


People also ask

How do I get out of backslash in Jenkins?

If your intent is to have literal backslashes in the resulting string, you need to escape the backslashes. That is, use a double-backslash ( \\ ) to substitute for one literal backslash.

How do you escape a quote in Jenkinsfile?

You need to escape twice, once the quote for the shell with a slash, and once that slash with a slash for groovy itself.

What is the format of Jenkinsfile?

IntelliJ can be configured to parse Jenkinsfile as a regular Groovy file, as explained in this question or this article. This allows to use standard Groovy formatting and syntax check. However, you might want to consider using Replay Pipeline functionality in your Jenkins instance instead.

What does sh do in Jenkinsfile?

On Linux, BSD, and Mac OS (Unix-like) systems, the sh step is used to execute a shell command in a Pipeline.


2 Answers

The '\' character is a special character in Groovy. If you tried to compile this kind of code with the normal Groovy compiler, it would give you a better error message. The easiest way to handle it would be to escape it:

"""
  rm -r /mnt/x/some/directory/Problem\\ 1.0/path
""" 
like image 94
mkobit Avatar answered Sep 17 '22 06:09

mkobit


You can modify the shell command as follows:

      sh """
        rm -r /mnt/x/some/directory/Problem""" +  """ 1.0/path"""

Provide space before 1.0 as required. Hope this helps.

like image 44
Here_2_learn Avatar answered Sep 21 '22 06:09

Here_2_learn