Functions group commands and accept positional parameters $1, $2, …—similar spirit to Python functions but without typed signatures.
Define and call
greet() {
echo "Hello, $1"
}
greet "Ada"
greet "Lin"$1 is the first argument; $@ is all arguments as separate words.
Return exit status
is_even() {
local n=$1
(( n % 2 == 0 ))
}
if is_even 4; then echo "even"; else echo "odd"; fiFunctions return the exit status of the last command—use return N explicitly when needed.
local variables
counter=0
bump() {
local counter=1
counter=$((counter + 1))
echo "inside: $counter"
}
bump
echo "outside: $counter"local avoids clobbering outer variables—good habit in larger scripts.
Important interview questions and answers
- Q: How do functions receive args?
A: Positional parameters $1, $2, … and $@ for all. - Q: What does local do?
A: Creates a variable scoped to the function body.
Self-check
- What variable holds the first argument?
- How does a function signal success/failure without print?
Tip: Use local for temporaries—compare with Python local scope habits from Python.
Interview prep
- How to pass args?
Positional $1, $2, ... and $@ for all.
- local keyword?
Creates function-scoped variables.