Objective

Define reusable functions in bash scripts, pass arguments, return values, use local variables, and source function libraries.

Tools & Technologies

  • function
  • local
  • return
  • source
  • $1 $2 $@

Key Commands

function greet() {
local VAR=value
return 0
source functions.sh
greet 'Alice'

Architecture Overview

graph LR CALLER[Main Script\ngreet Alice] -->|call + args| FUNC[greet function\n$1=Alice] FUNC -->|local vars| LOCAL[local NAME=$1] LOCAL -->|execute| BODY[echo Hello $NAME] BODY -->|return code| EXIT[return 0] EXIT -->|$?| CALLER style FUNC fill:#1a1a2e,stroke:#00d4ff,color:#e0e0e0 style LOCAL fill:#181818,stroke:#1e1e1e,color:#888

Step-by-Step Process

01
Define and Call Functions

Functions must be defined before they are called. Arguments are positional: $1, $2, $@.

#!/bin/bash
greet() {
  local NAME=$1
  echo "Hello, $NAME!"
}

# Call the function
greet 'Alice'
greet 'Bob'

# With multiple arguments
log_msg() {
  echo "[$(date +%T)] [$1] $2"
}
log_msg 'INFO' 'Script started'
02
Return Values

Bash functions return exit codes (0-255) via return. To return string data, use command substitution.

is_even() {
  [ $(($1 % 2)) -eq 0 ] && return 0 || return 1
}
if is_even 4; then echo 'even'; fi

# Return a string via stdout + command substitution
get_date() {
  date +%Y-%m-%d
}
TODAY=$(get_date)
echo "Today is $TODAY"
03
Local Variables

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

COUNTER=10  # global

increment() {
  local COUNTER=$1  # local — doesn't affect global
  ((COUNTER++))
  echo $COUNTER
}

increment $COUNTER  # prints 11
echo $COUNTER       # still 10 — global unchanged
04
Function Libraries

Store reusable functions in a separate file and source it.

# File: lib/utils.sh
log()    { echo "[$(date +%T)] $*"; }
die()    { log "ERROR: $*"; exit 1; }
check()  { command -v "$1" >/dev/null || die "$1 not found"; }

# Main script
source lib/utils.sh
check curl
check jq
log 'Starting backup...'

Challenges & Solutions

  • Function variables are global by default — always use local
  • return only sets $? — use echo + command substitution to return strings

Key Takeaways

  • Sourcing a file (. or source) runs it in the current shell — exports functions and variables
  • Put all functions at the top of the script, main logic at the bottom