Functions
Chapter 15: Functions
Section titled “Chapter 15: Functions”Overview
Section titled “Overview”Functions are reusable code blocks that perform specific tasks. They are essential for organizing code, avoiding repetition, and creating modular scripts. This chapter covers function declaration, parameters, return values, scope, and best practices for DevOps scripts.
Function Basics
Section titled “Function Basics”Function Declaration
Section titled “Function Declaration”#!/usr/bin/env bash# Method 1: function keywordfunction greet { echo "Hello, World!"}
# Method 2: parentheseshello() { echo "Hello!"}
# Call functiongreethelloFunction Parameters
Section titled “Function Parameters”Passing Arguments
Section titled “Passing Arguments”#!/usr/bin/env bashgreet() { local name="$1" echo "Hello, $name!"}
greet "Alice"greet "Bob"Multiple Parameters
Section titled “Multiple Parameters”#!/usr/bin/env bashadd() { local a="$1" local b="$2" local sum=$((a + b)) echo "$sum"}
result=$(add 5 3)echo "5 + 3 = $result"Return Values
Section titled “Return Values”Using echo
Section titled “Using echo”#!/usr/bin/env bashget_status() { local status="$1" case "$status" in 200) echo "OK" ;; 404) echo "Not Found" ;; 500) echo "Error" ;; *) echo "Unknown" ;; esac}
status=$(get_status 200)echo "Status: $status"Using Return
Section titled “Using Return”#!/usr/bin/env bashis_valid() { local value="$1" if [ "$value" -gt 0 ]; then return 0 # Success else return 1 # Failure fi}
if is_valid 10; then echo "Valid"else echo "Invalid"fiLocal Variables
Section titled “Local Variables”#!/usr/bin/env bashglobal="I'm global"
test_scope() { local local_var="I'm local" global="Modified global" echo "Inside: global=$global, local=$local_var"}
test_scopeecho "Outside: global=$global"# echo "$local_var" # Would error - not visiblePractical Examples
Section titled “Practical Examples”Example 1: Service Checker
Section titled “Example 1: Service Checker”#!/usr/bin/env bashcheck_service() { local service="$1"
if systemctl is-active --quiet "$service"; then echo "✓ $service is running" return 0 else echo "✗ $service is NOT running" return 1 fi}
# Usagecheck_service "nginx"check_service "postgresql"check_service "redis"Example 2: Logging Function
Section titled “Example 2: Logging Function”#!/usr/bin/env bashlog() { local level="$1" shift local message="$*" local timestamp=$(date '+%Y-%m-%d %H:%M:%S') echo "[$timestamp] [$level] $message"}
log "INFO" "Application started"log "WARN" "Memory usage high"log "ERROR" "Connection failed"Example 3: Validation Function
Section titled “Example 3: Validation Function”#!/usr/bin/env bashis_number() { [[ "$1" =~ ^[0-9]+$ ]]}
is_ip() { local ip="$1" [[ "$ip" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]}
validate_port() { local port="$1" is_number "$port" && [ "$port" -ge 1 ] && [ "$port" -le 65535 ]}
# Usageif is_number "8080"; then echo "Valid number"fi
if is_ip "192.168.1.1"; then echo "Valid IP"fi
if validate_port "80"; then echo "Valid port"fiAdvanced Topics
Section titled “Advanced Topics”Function Arrays
Section titled “Function Arrays”#!/usr/bin/env bashget_servers() { local servers=("web01" "web02" "db01") echo "${servers[@]}"}
mapfile -t server_list < <(get_servers)echo "Servers: ${server_list[@]}"Recursive Functions
Section titled “Recursive Functions”#!/usr/bin/env bashfactorial() { local n="$1" if [ "$n" -le 1 ]; then echo 1 else local prev=$(factorial $((n - 1))) echo $((n * prev)) fi}
echo "Factorial of 5: $(factorial 5)"Summary
Section titled “Summary”In this chapter, you learned about:
- ✅ Function declaration
- ✅ Passing parameters
- ✅ Return values
- ✅ Local variables and scope
- ✅ Practical examples
- ✅ Function arrays
- ✅ Recursive functions
- ✅ Best practices
Exercises
Section titled “Exercises”Level 1: Basics
Section titled “Level 1: Basics”- Create a function that prints a greeting
- Write a function that adds two numbers
- Create a function that checks if a file exists
Level 2: Intermediate
Section titled “Level 2: Intermediate”- Implement a logging function
- Create validation functions
- Build a service checker function
Level 3: Advanced
Section titled “Level 3: Advanced”- Implement a recursive function
- Create a function library
- Build a modular script with functions
Next Steps
Section titled “Next Steps”Continue to the next chapter to learn about scope and variable visibility.
Previous Chapter: Input/Output Next Chapter: Scope and Variable Visibility