Bash Functions and Scripts
Overview
Functions in Bash make scripts reusable and easier to maintain. Well-structured scripts support reliable Linux automation.
Function Practices
- Keep functions small and purpose-driven
- Pass parameters explicitly
- Return status codes, print structured output
- Centralize shared utility functions
flowchart TD
A[Main Script] --> B[validate_input]
A --> C[run_backup]
A --> D[send_report]
Practical Example
validate_file() {
local path="$1"
[[ -f "$path" ]] || { echo "Missing file: $path"; return 1; }
}
run_backup() {
local source="$1"
local target="$2"
rsync -a "$source" "$target"
}
Production Example
Infrastructure teams often maintain shared Bash libraries for standardized logging, retries, and command wrappers.
Common Pitfalls
- Using global variables unintentionally
- Not handling function return codes
- Mixing business logic with logging and formatting concerns
Key Takeaways
- Functions improve maintainability and reuse in Bash scripts.
- Explicit parameters and return codes increase reliability.
- Shared libraries help enforce team-wide standards.