Concept Flow - Calling functions
Define function
Call function
Execute function body
Return to caller
Continue main script
First, you define a function, then you call it. The script jumps to the function, runs its commands, then returns to continue.
greet() {
echo "Hello, friend!"
}
greet| Step | Action | Evaluation | Output |
|---|---|---|---|
| 1 | Define function greet | Function stored | |
| 2 | Call greet | Jump to greet function | |
| 3 | Execute echo inside greet | Print message | Hello, friend! |
| 4 | Return from greet | Back to main script | |
| 5 | End of script | No more commands |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|---|
| greet (function) | undefined | defined | called | executed | returned | defined |
Define a function with name() { commands; }
Call it by writing its name alone.
Calling jumps to function, runs commands, then returns.
Functions do not run when defined, only when called.
Use functions to reuse code and organize scripts.greet?greet on a line by itself. matches the correct way: just the function name alone.greet on a line by itself. -> Option Chello in Bash?name() { commands; } or with the keyword function followed by name and braces.hello() { echo "Hi" }, which is correct. hello { echo "Hi" } misses the () after the name. def hello() { echo "Hi" } uses Python syntax. function hello() echo "Hi" misses braces.say_hello() {
echo "Hello, $1!"
}
say_hello Alicesay_hello prints "Hello," followed by the first argument $1.$1 becomes "Alice".greet() {
echo "Hi $name"
}
greet John$name, but no variable named name is set or passed.$1 to access it.sum that takes two numbers as arguments and prints their sum. Which script correctly calls the function and prints the result?$((expression)). Inside, use $1 and $2 for arguments.sum() {
echo $(($1 + $2))
}
sum 3 5 correctly sums $1 + $2. sum() {
echo $1 + $2
}
sum 3 5 prints literal string with plus sign. sum() {
echo $((1 + 2))
}
sum 3 5 adds 1 and 2 literally, ignoring arguments. sum() {
echo $1 $2
}
sum 3 5 prints arguments separated by space.Pass the test and this pattern moves unknown