๐งฑ Extended Functions and Libraries
Functions encapsulate reusable logic. Libraries organize shared code across multiple scripts. This section covers both in depth.
๐งญ Defining Functions
Two syntaxes (both equivalent):
1 2 3 4 5 6 7 8 9 | |
Call the function:
1 | |
๐งช Passing Arguments
Inside functions, positional parameters are local:
1 2 3 4 5 6 7 8 9 | |
Output:
1 2 3 4 5 | |
๐ง Returning Values
Shell functions don't return values like other languages. Instead:
Method 1: Echo Output (Most Common)
1 2 3 4 5 6 | |
Method 2: Global Variable
1 2 3 4 5 6 | |
โ ๏ธ Modifies global scope โ use carefully.
Method 3: Exit Code
1 2 3 4 5 6 7 8 9 10 | |
๐งช Local Variables
Prevent pollution of global scope:
1 2 3 4 5 6 7 8 9 10 11 | |
local ensures variables don't leak outside the function.
๐ง Organizing Libraries
Simple Library File
lib/utils.sh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
Including Libraries
1 2 3 4 5 6 7 8 9 10 11 12 | |
The . command (or source) loads functions into current shell context.
๐งช Advanced Library Patterns
Namespaced Functions
Avoid name collisions:
1 2 3 4 5 6 7 8 9 10 11 | |
Prefix with module name for clarity.
Conditional Loading
Load only if not already defined:
1 2 3 | |
Or check function existence:
1 2 3 | |
๐ง Recursive Functions
Bash supports recursion (enable with shopt -s extdebug in some cases):
1 2 3 4 5 6 7 8 9 10 11 | |
โ ๏ธ Deep recursion may hit stack limits โ use iteration for large inputs.
๐งช Anonymous Functions (Bash 4.4+)
Define inline functions:
1 2 3 4 5 6 7 8 9 | |
๐งพ Portability Notes
| Feature | POSIX | Bash | Zsh |
|---|---|---|---|
| Function definition | โ | โ | โ |
local variables |
โ | โ | โ |
$FUNCNAME |
โ | โ | โ |
| Recursion | โ ๏ธ | โ | โ |
| Anonymous functions | โ | โ | โ |
| Arrays as args | โ | โ | โ |
๐งพ Summary
- Use functions to avoid code duplication.
- Always use
localfor variables inside functions. - Return values via stdout or exit codes.
- Organize shared code in library files.
- Source libraries with
.orsource. - Prefix function names to avoid collisions.
๐ Continue to: Error Handling