How to use regex in pipeline

Hi,

I want to use regex in the pipeline but I’m seeing build failures because of $ symbol. Can you please let me know how can I use that ? Below is code snippet.

sshagent () {
    sh """
        #!/bin/bash
        git clone <repo>
        cd repo
        if git branch -r | grep -E "$branchName($|\s)"; then
              echo "Found"
        fi
    """
}

If I escape $ by using , the grep command is not working. Btw, I have to also escape \s as \s.

My final goal is to make sure to find the branch which is ending with specific branchName.

Thanks in advance,
SheshaChandra

You’re using double quotes for the sh step. Unless you want to have string interpolation done by groovy you should use single quotes. Then you don’t need to escape $ and \

sh '''
 ...
''' 

@mawinter69 , Thanks for replying back.
I have few variables in the shell script which needs interpolation and so cannot use single quotes as that doesn’t work.
For ex., $branchName

You could set them as env variables with
withEnv step.

If you want to stay with groovy interpolation you will need to quote the $ from groovy

sshagent () {
    sh """
        #!/bin/bash
        git clone <repo>
        cd repo
        if git branch -r | grep -E "$branchName(\$|\\s)"; then
              echo "Found"
        fi
    """
}
1 Like

Thanks. Let me try this and will update…