Defining Functions
Functions package reusable logic in Bash scripts. You can declare functions using either the function name() or name() style, then call them like commands.
Two Declaration Styles
Both styles are widely used. Pick one and be consistent:
- With keyword:
function foo() { ... } - Without keyword:
foo() { ... }
Output
Click Run to execute your code
Tip: Functions inherit the parent shell environment. To avoid accidental global changes, use
local variables inside functions.
Pro Tip: Keep function names lowercase with hyphens or underscores (e.g.,
print_summary) and group related helpers together for readability.
Caution: A function that runs
set -e or unguarded commands can terminate your whole script. Handle errors explicitly or return status codes.
Local vs Global (Preview)
By default, variables are global in Bash. Use local inside functions to limit scope:
Output
Click Run to execute your code
Common Mistakes
1) Forgetting local in helpers
# Wrong: overwrites global var
name="Global"
set_name() { name="$1"; }
set_name "Bob"
echo "$name" # Global changed unintentionally
# Correct: use local inside function
name="Global"
set_name() { local name="$1"; echo "local=$name"; }
set_name "Bob"
echo "$name" # Still "Global"
2) Relying on return for data
# Wrong: return is only 0..255
add() { return $(( $1 + $2 )); }
add 200 100 # Overflow risk
# Correct: echo and capture output
add() { echo $(( $1 + $2 )); }
sum=$(add 200 100)
echo "$sum"
Exercise: Greeting Function
Task: Write a function greet that prints "Hello, NAME". If no argument is provided, default to "World".
- Support zero or one argument.
- Do not modify any global variables.
Output
Click Run to execute your code
Show Solution
greet() {
local name=${1:-World}
echo "Hello, $name"
}
greet
greet "Alice"
Summary
- Declare functions with either
function name()orname(). - Call functions like regular commands:
my_func arg1 arg2. - Use
localto prevent side effects on global variables.
What's Next?
Next, pass data into functions and iterate arguments in Function Parameters.
Enjoying these tutorials?