Functions
Define reusable code blocks
Basic function
Simple function with parameter
#!/bin/bash
function greet() {
echo "Hello, $1!"
}
greet "World"
Function with return value
Function that returns a value
#!/bin/bash
function add() {
local result=$(( $1 + $2 ))
echo $result
}
sum=$(add 5 3)
echo "Sum is: $sum"
Function with local variables
Function with local variables and error handling
#!/bin/bash
function process_file() {
local filename=$1
local temp_file="/tmp/processed_$filename"
if [ -f "$filename" ]; then
echo "Processing $filename"
# Process file here
else
echo "File $filename not found"
return 1
fi
}
Function with default parameters
Function with default parameter values
#!/bin/bash
greet() {
local name=${1:-"World"}
local greeting=${2:-"Hello"}
echo "$greeting, $name!"
}
greet
greet "Alice"
greet "Bob" "Hi"
Function with variable arguments
Function that accepts variable number of arguments
#!/bin/bash
sum() {
local total=0
for num in "$@"; do
total=$((total + num))
done
echo $total
}
result=$(sum 1 2 3 4 5)
echo "Sum: $result"
Function with error handling
Function with error handling and return codes
#!/bin/bash
safe_divide() {
if [ $2 -eq 0 ]; then
echo "Error: Division by zero" >&2
return 1
fi
echo $(( $1 / $2 ))
}
result=$(safe_divide 10 2)
echo "Result: $result"
safe_divide 10 0
Recursive function
Recursive function example
#!/bin/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)"