Skip to content

Functions

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_basic.sh
#!/usr/bin/env bash
# Method 1: function keyword
function greet {
echo "Hello, World!"
}
# Method 2: parentheses
hello() {
echo "Hello!"
}
# Call function
greet
hello

function_params.sh
#!/usr/bin/env bash
greet() {
local name="$1"
echo "Hello, $name!"
}
greet "Alice"
greet "Bob"
function_multi.sh
#!/usr/bin/env bash
add() {
local a="$1"
local b="$2"
local sum=$((a + b))
echo "$sum"
}
result=$(add 5 3)
echo "5 + 3 = $result"

function_return.sh
#!/usr/bin/env bash
get_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"
function_return_code.sh
#!/usr/bin/env bash
is_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"
fi

local_var.sh
#!/usr/bin/env bash
global="I'm global"
test_scope() {
local local_var="I'm local"
global="Modified global"
echo "Inside: global=$global, local=$local_var"
}
test_scope
echo "Outside: global=$global"
# echo "$local_var" # Would error - not visible

check_service.sh
#!/usr/bin/env bash
check_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
}
# Usage
check_service "nginx"
check_service "postgresql"
check_service "redis"
logging.sh
#!/usr/bin/env bash
log() {
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"
validation.sh
#!/usr/bin/env bash
is_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 ]
}
# Usage
if 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"
fi

func_array.sh
#!/usr/bin/env bash
get_servers() {
local servers=("web01" "web02" "db01")
echo "${servers[@]}"
}
mapfile -t server_list < <(get_servers)
echo "Servers: ${server_list[@]}"
recursion.sh
#!/usr/bin/env bash
factorial() {
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)"

In this chapter, you learned about:

  • ✅ Function declaration
  • ✅ Passing parameters
  • ✅ Return values
  • ✅ Local variables and scope
  • ✅ Practical examples
  • ✅ Function arrays
  • ✅ Recursive functions
  • ✅ Best practices

  1. Create a function that prints a greeting
  2. Write a function that adds two numbers
  3. Create a function that checks if a file exists
  1. Implement a logging function
  2. Create validation functions
  3. Build a service checker function
  1. Implement a recursive function
  2. Create a function library
  3. Build a modular script with functions

Continue to the next chapter to learn about scope and variable visibility.


Previous Chapter: Input/Output Next Chapter: Scope and Variable Visibility