Problem Statement
Explain advanced function concepts including return values, variable scope, function libraries, and recursive functions.
Explanation
Return values: functions return exit status (0-255) via return N, not actual values. Get output with command substitution: RESULT=$(function_name). Echo values in function: function get_value() { echo "result"; }, VALUE=$(get_value). Multiple return values: echo space-separated values, split with read: read var1 var2 <<< "$(function)".
Variable scope: variables are global by default, visible everywhere. Local variables with local keyword exist only in function:
```bash
function test() {
local LOCAL_VAR="function scope"
GLOBAL_VAR="modified globally"
}
test
echo $GLOBAL_VAR # Visible
echo $LOCAL_VAR # Empty
```
Use local for all function variables preventing side effects. Export doesn't affect function scope (only child processes).
Function libraries: source or . loads functions from external files. Create library file:
```bash
# lib/common.sh
log() { echo "[$(date)] $*"; }
error() { echo "ERROR: $*" >&2; exit 1; }
```
Source in scripts: source lib/common.sh or . lib/common.sh. Check file exists: [ -f lib/common.sh ] && source lib/common.sh || { echo "Library not found"; exit 1; }. Organize related functions into libraries for reuse across scripts.
Recursive functions: function calls itself. Example factorial:
```bash
factorial() {
local n=$1
if ((n <= 1)); then
echo 1
else
echo $((n * $(factorial $((n-1)))))
fi
}
```
Need base case to prevent infinite recursion. Use for tree traversal, directory processing, or algorithms naturally recursive. Bash has limited stack depth (~1000 levels). For deep recursion, consider iteration or external programs.
Best practices: one function, one purpose; meaningful names; document parameters and return values; handle errors; validate inputs; use local variables; return early on errors; keep functions short (<50 lines). Understanding advanced function usage enables writing modular, maintainable, professional scripts.
Practice Sets
This question appears in the following practice sets: