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. 


On Wednesday, October 18, 2017 at 2:46:40 PM UTC-6, Jeff Pearce wrote:
>
> 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') }
>
>
>                 )
>             }
>         }
>     }
> }
>
>

-- 
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 [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/jenkinsci-users/49e127fd-29cb-44a6-872e-a608b409b4ed%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to