This session teaches how to structure large scripts effectively by creating and utilizing reusable functions, improving readability, maintainability, and reducing code duplication.
Learning Objectives
- Define and call simple Bash functions.
- Understand and manage variable scope within functions (local vs. global).
- Pass arguments to functions and handle return values.
- Learn to modularize scripts by sourcing function definitions from external files.
Topics Covered
1. Defining Functions
- Syntax: Defining functions using
function name { ... }or the more portablename () { ... }. - Execution: Calling a function simply by its name within the script.
2. Function Arguments and Return Values
- Arguments: Functions treat arguments just like scripts, using
$1,$2, etc. - Passing Arrays (Advanced):
bash
my_func() {
local -a arr=("${@}")
echo "First element: ${arr[0]}"
}
list=("apple" "banana")
my_func "${list[@]}"
- Return Values:
- Functions return an exit code using
return(0-255). - Data can be "returned" via
echoand command substitution. - Namerefs (Very Advanced): Using
declare -nto modify a variable passed by name.
3. Variable Scope and Best Practices
- Global vs Local: Always use
localfor variables inside functions to avoid "polluting" the global namespace. - The
mainPattern: For larger scripts, wrap your logic in amain()function.
bash
main() {
setup
execute_task
}
main "$@"
4. Script Modularity
- Sourcing Files: Using the
sourcecommand or the dot operator (.) to execute another script file in the current shell environment, making its functions available. This is key for creating script libraries.
Lab/Assessment Focus
Goal: Create a modular calculator tool.
lib_math.sh: Create a library containing functions foradd,multiply, and a recursivefactorialfunction.app.sh:- Sources
lib_math.sh. - Uses a
main()function to parse arguments. - Checks if the first argument is "fact" or "calc".
- Calls the appropriate function and handles errors if the input is not a number.
- Sources
Advanced Topic References
- Bash Function Best Practices: Best practices for complex function design.
- The Bash
localKeyword Explained: Official documentation on variable scope. - Sourcing vs Executing Scripts: When to use
sourcevs./script.sh.