Gosia Wiśniewska
Gosia Wiśniewska

Reputation: 47

Creating complex environment variables

Out of environment variable WORKSPACE I need to extract part of the string after last '\'. For example I have something1\something2\something3 and I need to extract something3 and save it as environment variable in Jenkinsfile.

I've tried this approach:

groovy
environment {
        service = "${(env.WORKSPACE).substring((env.WORKSPACE).lastIndexOf('\'), (env.WORKSPACE).length())}"
    }

But while running it I get an error:

WorkflowScript: 20: expecting ''', found '\n' @ line 20, column 113.
    (env.WORKSPACE).length())}"""
                                 ^

1 error

Upvotes: 1

Views: 296

Answers (1)

tim_yates
tim_yates

Reputation: 171184

In Groovy and many other languages, \ is an escape character. So in the lastIndexOf, the '\' is opening a string, then escaping the closing '

You just need to escape the \ (escape the escape)

"${(env.WORKSPACE).substring((env.WORKSPACE).lastIndexOf('\\'), (env.WORKSPACE).length())}"

You can also take this out of a string, as it's already a string:

service = env.WORKSPACE.substring(env.WORKSPACE.lastIndexOf('\\'), env.WORKSPACE.length())

Should be enough

Upvotes: 2

Related Questions