0
0
Bash Scriptingscripting~10 mins

Function definition in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Function definition
Start script
Define function
Call function
Execute function body
Return to main script
End script
The script starts by defining a function, then calls it, executes its body, and returns to the main script until the script ends.
Execution Sample
Bash Scripting
greet() {
  echo "Hello, $1!"
}

greet Alice
Defines a function greet that prints a hello message with the given name, then calls it with 'Alice'.
Execution Table
StepActionEvaluationOutput
1Define function greetFunction greet is stored
2Call function greet with argument 'Alice'Function greet starts
3Execute echo "Hello, $1!" inside greetSubstitute $1 with 'Alice'Hello, Alice!
4Return from function greetBack to main script
5Script endsNo more commands
💡 Script ends after function call completes
Variable Tracker
VariableStartAfter Call 1Final
$1undefinedAliceundefined after function ends
Key Moments - 2 Insights
Why does $1 have the value 'Alice' only inside the function?
Because $1 is a special variable holding the first argument passed to the function, as shown in execution_table step 3.
What happens if we call the function without arguments?
Then $1 is empty inside the function, so the echo prints 'Hello, !' as no argument is passed, similar to step 3 but with empty substitution.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is printed at step 3?
Agreet Alice
BHello, $1!
CHello, Alice!
DFunction greet is stored
💡 Hint
Check the Output column at step 3 in the execution_table
At which step does the function greet start executing?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the Action and Evaluation columns to find when the function starts
If we call greet with 'Bob' instead of 'Alice', what changes in variable_tracker after call 1?
A$1 becomes Alice
B$1 becomes Bob
C$1 remains undefined
DNo change
💡 Hint
Refer to variable_tracker row for $1 and imagine replacing 'Alice' with 'Bob'
Concept Snapshot
Function definition in bash:
function_name() {
  commands
}
Call with: function_name args
$1, $2... hold arguments inside function
Function runs when called, not when defined
Use functions to reuse code blocks
Full Transcript
This example shows how to define a function in bash scripting. The function greet is defined with greet() { ... }. Inside, it uses echo to print a message including the first argument $1. When the script calls greet Alice, the function runs and prints 'Hello, Alice!'. The variable $1 holds the argument only inside the function. After the function finishes, the script continues and ends. This teaches how functions are defined, called, and how arguments work in bash.