jenkins-pipelinejenkins-groovygroovyshell

Groovy Executing shell \ & Regex inside Jenkinsfile


I'm running Jenkinsfile to grep pm2 services from a remote server, so I use the grep utility to find the pm2 service-name. Still, Jenkins Groovy does not understand the bash commands and gives errors before building the pipeline.

Here is My Pipeline

pipeline {
    agent any

    parameters {
        string(defaultValue: '', description: 'List of PM2 applications', name: 'PM2_Applications')
    }

    stages {
    stage('SSH transfer') {
        steps([$class: 'BapSshPromotionPublisherPlugin']) {
            sshPublisher(
                continueOnError: false, failOnError: true,
                publishers: [
                    sshPublisherDesc(
                        configName: "server-config",
                        verbose: true,
                        transfers: [
                            sshTransfer(execCommand: "pm2 ls | grep -vE '^\s*id\s+' | awk '{print $4}'"),
                           
                           
                        ]
                    )
                ]
            )
        }
    }

}
}

Error I'm Getting:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 18: unexpected char: '\' @ line 18, column 75.
   Command: "pm2 ls | grep -vE '^\s*id\s+' 

Expected Output: It should run the pm2 command with grep and it would give the actual output of the command.


Solution

  • Backslash \ is an escape character in Groovy, to use it literally you need to double it \\. Same with $, you need to escape it - \$.