Script Valley
Linux & Bash for Developers
Bash Scripting FundamentalsLesson 3.5

Bash functions: how to write reusable code

function syntax, local variables, return values, function arguments, sourcing scripts, libraries, recursive functions

Functions Avoid Repetition in Scripts

A Bash function groups commands under a name. Declare it once, call it anywhere in the script. Functions reduce duplication, improve readability, and make scripts testable.

Defining and Calling Functions

#!/bin/bash

# Function definition — must come before first call
log_info() {
  local MESSAGE="$1"
  local TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
  echo "[$TIMESTAMP] INFO: $MESSAGE"
}

log_error() {
  local MESSAGE="$1"
  echo "ERROR: $MESSAGE" >&2  # write errors to stderr
  return 1
}

# Call functions
log_info "Script started"
log_info "Processing files..."

if ! create_backup; then
  log_error "Backup failed"
  exit 1
fi

local Variables and Return Values

Always declare variables inside functions with local. Without it, variables are global and can overwrite values set elsewhere in the script. Bash functions cannot return strings — they return integer exit codes (0-255). To return a string, echo it and capture with command substitution.

get_timestamp() {
  echo $(date '+%Y%m%d_%H%M%S')
}

# Capture the returned string
TS=$(get_timestamp)
echo "Backup name: backup_$TS.tar.gz"

Sourcing Shared Libraries

# In utils.sh: define shared functions
# In main.sh: load them
source ./utils.sh
# or
. ./utils.sh