Scoping of variables in for loop?

20 views
Skip to first unread message

Jeff Pearce

unread,
Oct 18, 2017, 4:46:40 PM10/18/17
to Jenkins Users
I was wondering whether someone could explain something to me.  The job below fails, because it seems like the parallel steps are sharing the same copy of the variable i in the for loop.

If I change line 3 to for (i = 0; i < 30; i++) then the job passes. Is this expected? It seems like maybe the variable is global if you don't add the "def".

def testFunction(theEcho) {
   
def previous = -1;
   
for (i = 0; i < 30; i++) {
       
if (i != previous + 1) {
            error
"current '$i' != previous '$previous' + 1"
       
}
        previous
= i
        sh
"echo $i"
        sleep
(1)
     
}
}
pipeline
{
    agent any
    stages
{
        stage
('stage 1') {
            steps
{
                parallel
(
                   
'step 1' : { testFunction('echo hello world 1') },
                   
'step 2' : { testFunction('echo hello world 2') },
                   
'step 3' : { testFunction('echo hello world 3') },
                   
'step 4' : { testFunction('echo hello world 4') },
                   
'step 5' : { testFunction('echo hello world 5') },
                   
'step 6' : { testFunction('echo hello world 6') },
                   
'step 7' : { testFunction('echo hello world 7') },
                   
'step 8' : { testFunction('echo hello world 8') },
                   
'step 9' : { testFunction('echo hello world 9') },
                   
'step 10' : { testFunction('echo hello world 10') }


               
)
           
}
       
}
   
}
}

Robert Hales

unread,
Oct 18, 2017, 7:05:23 PM10/18/17
to Jenkins Users
Your question is a little confusing, because the line in the text is exactly the same as the line in your code. But I think you must mean that it fails if you don't `def i`. 

Yes, if you don't declare the variable, then it will be in something similar to a global scope for this purpose. I think it actually is called a binding variable and gets scoped to the 'script' level, but I don't quite understand how the pipeline script relates back to straight groovy. So for your purposes, yes, it is global if you don't declare the variable. It is the same with your `previous` variable. If that wasn't declared, it would not work like you expect. 

Jeff Pearce

unread,
Oct 18, 2017, 8:14:45 PM10/18/17
to Jenkins Users
Thanks the reply Robert, that was indeed a typo in the original post - sorry about any confusion.
Reply all
Reply to author
Forward
0 new messages