function Command

Define reusable functions in shell scripts to create modular, maintainable code that can be called multiple times with different parameters.

Syntax

function name() { commands } name() { commands } function name { commands }

The function command provides multiple syntax options for defining reusable functions in shell scripts, allowing for better code organization and reusability.

Basic Usage

Simple function definition

# Define a simple function function hello() { echo "Hello, World!" } # Call the function hello # Alternative syntax goodbye() { echo "Goodbye!" }

Basic function definition and calling syntax

Functions with parameters

# Function with parameters function greet() { local name=$1 echo "Hello, $name!" } # Call with parameter greet "John" greet "Alice" # Function with multiple parameters function add() { local a=$1 local b=$2 echo $((a + b)) } add 5 3

Define functions that accept and use parameters

Functions with return values

# Function that returns a value function multiply() { local a=$1 local b=$2 echo $((a * b)) } # Capture return value result=$(multiply 4 6) echo "Result: $result" # Function with exit status function check_file() { if [ -f "$1" ]; then return 0 else return 1 fi } check_file "test.txt" if [ $? -eq 0 ]; then echo "File exists" fi

Functions that return values or exit status codes

Advanced Usage

Local variables and scope

# Using local variables function process_data() { local input_file=$1 local output_file=$2 local temp_dir="/tmp/process_$$" mkdir -p "$temp_dir" # Process files... rm -rf "$temp_dir" } # Variables are local to function global_var="outside" function test_scope() { local global_var="inside" echo "Inside: $global_var" } test_scope echo "Outside: $global_var"

Control variable scope and prevent conflicts

Function libraries and sourcing

# functions.sh - function library #!/bin/bash function backup_file() { local source=$1 local backup_dir=${2:-/backup} if [ -f "$source" ]; then cp "$source" "$backup_dir/" echo "Backed up: $source" fi } function log_message() { local message=$1 local level=${2:-INFO} echo "$(date): [$level] $message" } # main.sh - use the library #!/bin/bash source ./functions.sh backup_file "important.txt" log_message "Backup completed" "SUCCESS"

Create reusable function libraries for multiple scripts

Error handling and validation

# Function with error handling function safe_operation() { local input=$1 # Validate input if [ -z "$input" ]; then echo "Error: Input is required" >&2 return 1 fi # Check if input is a number if ! [[ "$input" =~ ^[0-9]+$ ]]; then echo "Error: Input must be a number" >&2 return 1 fi # Perform operation echo "Processing: $input" return 0 } # Use error handling if safe_operation "123"; then echo "Operation successful" else echo "Operation failed" fi

Add input validation and error handling to functions

Practical Examples

System administration functions

# Check service status function check_service() { local service_name=$1 if systemctl is-active --quiet "$service_name"; then echo "$service_name is running" return 0 else echo "$service_name is not running" return 1 fi } # Backup function function backup_directory() { local source_dir=$1 local backup_dir=$2 local timestamp=$(date +%Y%m%d_%H%M%S) if [ -d "$source_dir" ]; then tar -czf "${backup_dir}/backup_${timestamp}.tar.gz" "$source_dir" echo "Backup created: backup_${timestamp}.tar.gz" else echo "Source directory does not exist" return 1 fi }

Common administrative functions for system management

File processing functions

# Process text files function process_text_files() { local pattern=$1 local action=$2 for file in $pattern; do if [ -f "$file" ]; then case $action in "uppercase") tr '[:lower:]' '[:upper:]' < "$file" > "${file}.tmp" mv "${file}.tmp" "$file" ;; "lowercase") tr '[:upper:]' '[:lower:]' < "$file" > "${file}.tmp" mv "${file}.tmp" "$file" ;; *) echo "Unknown action: $action" return 1 ;; esac echo "Processed: $file" fi done }

File manipulation and processing functions

Utility functions

# Date formatting function function format_date() { local format=${1:-%Y-%m-%d} date +"$format" } # Color output function function colored_echo() { local color=$1 local message=$2 case $color in "red") echo -e "\033[31m$message\033[0m" ;; "green") echo -e "\033[32m$message\033[0m" ;; "yellow") echo -e "\033[33m$message\033[0m" ;; "blue") echo -e "\033[34m$message\033[0m" ;; *) echo "$message" ;; esac } # Usage colored_echo "green" "Success message" colored_echo "red" "Error message"

Common utility functions for enhanced output and formatting

Best Practices

Function Best Practices
  • Use descriptive function names that indicate purpose
  • Always use local variables to avoid conflicts
  • Validate input parameters at the beginning
  • Return meaningful exit codes for error handling
  • Document function purpose and parameters
  • Keep functions focused on single responsibilities
Common Pitfalls
  • Global variables - Avoid modifying global variables without local declaration
  • Long functions - Keep functions short and focused
  • Missing validation - Always validate input parameters
  • Hard-coded values - Use parameters instead of hard-coded values
  • No error handling - Always handle potential errors

See also