0
0
Jenkinsdevops~10 mins

Script blocks for Groovy in Jenkins - Step-by-Step Execution

Choose your learning style9 modes available
Process Flow - Script blocks for Groovy
Start Script Block
Define Variables & Logic
Execute Statements in Order
Return Last Expression Result
End Script Block
A Groovy script block runs code inside braces { } sequentially, defining variables and executing statements, returning the last expression's value.
Execution Sample
Jenkins
def result = {
  def x = 5
  def y = 10
  x + y
}
println(result())
Defines a script block that adds two numbers and prints the result.
Process Table
StepActionEvaluationResult
1Enter script blockStart block executionNo output yet
2Define xx = 5x = 5
3Define yy = 10y = 10
4Evaluate last expressionx + y15
5Return result from blockBlock returns 15result = closure returning 15
6Call result()Execute blockPrints 15
💡 Script block ends after last expression; calling result() runs the block and outputs 15
Status Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
xundefined5555
yundefinedundefined101010
resultundefinedundefinedundefinedclosureclosure returning 15
Key Moments - 2 Insights
Why does the script block return the value of the last expression?
In Groovy, a script block returns the value of its last evaluated expression automatically, as shown in step 4 of the execution_table where 'x + y' evaluates to 15.
What happens when we call result() after defining the script block?
Calling result() executes the script block code inside the closure, producing the output 15 as shown in step 6 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'y' after step 3?
Aundefined
B5
C10
D15
💡 Hint
Check the 'variable_tracker' table column 'After Step 3' for variable 'y'
At which step does the script block return its final value?
AStep 4
BStep 5
CStep 2
DStep 6
💡 Hint
Look at the 'execution_table' row where the block returns the value
If we change 'x' to 7, what will be the output when calling result()?
A17
B15
C10
D7
💡 Hint
Sum of x and y is returned; see 'variable_tracker' and 'execution_table' for how values combine
Concept Snapshot
Groovy script blocks use braces { } to group code.
They run statements in order and return the last expression's value.
Variables inside are local to the block.
Call the block like a function to execute it.
Useful for grouping logic in Jenkins pipelines.
Full Transcript
A Groovy script block is a group of code inside braces { } that runs sequentially. Inside, you can define variables and write expressions. The block automatically returns the value of the last expression it evaluates. For example, defining variables x and y inside the block and adding them returns their sum. When you assign this block to a variable like 'result', you get a closure. Calling result() runs the block and outputs the final value. This behavior is common in Jenkins pipelines to group and execute code chunks cleanly.