(Pipelines) String split; why isn't this working?

3,053 views
Skip to first unread message

Peter Berghold

unread,
Jan 8, 2018, 2:53:15 PM1/8/18
to Jenkins Users
Given an input of: /data/ci/jenkins/workspace/PeterBLaboratory/Test-unittestlibobjs-10/somesubdir/somefile.txt

I have a function:

   
    def basename(path){
        def pieces 
        
        pieces = path.split("/")
        
        context.sh 'echo first element: ' + pieces[0]
        context.sh 'echo path: ' + path
        context.sh 'echo parts: ' + pieces.size
        
        def idx
        idx = pieces.size - 1
        
        return pieces[idx]
    }

and I expect it to return the last element in a split array based on the character '/'

What I'm seeing instead is:
groovy.lang.MissingPropertyException: Exception evaluating property 'size' for java.util.Arrays$ArrayList, Reason: groovy.lang.MissingPropertyException: No such property: size for class: java.lang.String

what the heck is going on here?

It also looks like path.split is not behaving as I'd expect and returning an array of strings based on the delimiter. Thoughts folks?

Slide

unread,
Jan 8, 2018, 3:02:20 PM1/8/18
to jenkins...@googlegroups.com
This is off topic of what you are asking, but why not just use context.echo instead of context.sh? Also, use string interpolation:

context.echo "first element ${pieces[0]}"

Note: you must use double quotes for this to work. 

Also, you can def and assign on the same line:

def pieces = path.split('/').

path.split takes a regular expression, so you need to make sure you are escaping anything that needs to be escaped (in your case it doesn't look like anything does, just something to keep in mind).

--
You received this message because you are subscribed to the Google Groups "Jenkins Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jenkinsci-use...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/jenkinsci-users/CAArvnv3AbsixuXJ14epdqLOJFg5hspnwiCuDCAvyLx61dxLwRA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Slide

unread,
Jan 8, 2018, 3:07:38 PM1/8/18
to jenkins...@googlegroups.com
FYI, you want pieces.length, not pieces.size.String.split returns a String[], which you get the length of using .length


Reply all
Reply to author
Forward
0 new messages