Bash Functions - Definition, Arguments, Return Values, Scope

Learn to write reusable bash functions with arguments, return values, local variables, error handling, and practical patterns for modular shell scripts.

Control Flow

Detailed Explanation

Functions in Bash

Functions encapsulate reusable blocks of code. They accept arguments, can return values, and support local variables for proper scoping.

Function Definition

# Standard syntax
greet() {
  echo "Hello, $1!"
}

# Alternative syntax
function greet {
  echo "Hello, $1!"
}

# Call the function
greet "Alice"    # Hello, Alice!
greet "Bob"      # Hello, Bob!

Arguments

Functions access arguments using $1, $2, etc. (same as script arguments):

create_user() {
  local name="$1"
  local email="$2"
  local role="${3:-user}"    # default to "user"

  echo "Creating $role account for $name ($email)"
}

create_user "Alice" "alice@example.com" "admin"
create_user "Bob" "bob@example.com"

Return Values

Functions return exit codes (0-255). Use echo to output values:

# Return exit code
is_installed() {
  command -v "$1" > /dev/null 2>&1
}

if is_installed "docker"; then
  echo "Docker is available"
fi

# Return a value via echo
get_timestamp() {
  date +%s
}

TIMESTAMP=$(get_timestamp)

Local Variables

Use local to prevent variables from leaking into the global scope:

process_file() {
  local filename="$1"
  local line_count=0

  while IFS= read -r line; do
    line_count=$((line_count + 1))
  done < "$filename"

  echo "$line_count"
}

Error Handling in Functions

safe_delete() {
  local target="$1"

  if [ -z "$target" ]; then
    echo "Error: No target specified" >&2
    return 1
  fi

  if [ ! -e "$target" ]; then
    echo "Error: $target does not exist" >&2
    return 2
  fi

  rm -rf "$target"
  return 0
}

# Usage with error checking
if ! safe_delete "/tmp/cache"; then
  echo "Cleanup failed"
fi

Practical Patterns

# Logging function
log() {
  local level="$1"
  shift
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $*" | tee -a app.log
}

log "INFO" "Application starting"
log "ERROR" "Failed to connect to database"

# Cleanup trap
cleanup() {
  echo "Cleaning up temporary files..."
  rm -rf "$TEMP_DIR"
}
trap cleanup EXIT

TEMP_DIR=$(mktemp -d)
# ... rest of script

Use Case

Functions are the building blocks of well-organized bash scripts. They are used for logging utilities, input validation, error handling wrappers, deployment steps, configuration loading, and any repeated operation. Using functions makes scripts easier to read, test, and maintain.

Try It — Bash Cheat Sheet

Open full tool