Functions
KSH function definitions and usage
KSH basic function
KSH basic function with parameter
#!/bin/ksh
function greet {
typeset name=$1
print "Hello, $name!"
}
greet "World"
KSH function with return value
KSH function that returns a value
#!/bin/ksh
function add {
typeset a=$1 b=$2
typeset result=$((a + b))
print $result
}
sum=$(add 5 3)
print "Sum is: $sum"
KSH function with local variables
KSH function with local variables and cleanup
#!/bin/ksh
function process_file {
typeset filename=$1
typeset temp_dir="/tmp/processing"
typeset backup_file="${filename}.backup"
mkdir -p "$temp_dir"
cp "$filename" "$backup_file"
print "Processing $filename in $temp_dir"
rm -rf "$temp_dir"
}
process_file "data.txt"
KSH function with error handling
KSH function with error handling and return codes
#!/bin/ksh
function safe_divide {
typeset a=$1 b=$2
if (( b == 0 )); then
print "Error: Division by zero" >&2
return 1
fi
print $((a / b))
}
result=$(safe_divide 10 2)
print "Result: $result"
safe_divide 10 0
KSH function with default parameters
KSH function with default parameter values
#!/bin/ksh
function greet {
typeset name=${1:-"World"}
typeset greeting=${2:-"Hello"}
print "$greeting, $name!"
}
greet
greet "Alice"
greet "Bob" "Hi"
KSH function with variable arguments
KSH function that accepts variable number of arguments
#!/bin/ksh
function sum {
typeset total=0
for num in "$@"; do
total=$((total + num))
done
print $total
}
result=$(sum 1 2 3 4 5)
print "Sum: $result"