Script Valley
Bash Scripting for Developers
Functions and Script ArchitectureLesson 3.1

How to write and call Bash functions

function declaration syntax, calling functions, return values, return vs exit, function arguments $1 $2, local variables, function scope, overriding built-ins

Functions in Bash

Bash function call model

Bash functions group commands under a name. They use the same argument system as scripts — $1, $2, $@ — but scoped to the function call.

#!/usr/bin/env bash

# Declaration
greet() {
  local name="$1"   # local: stays inside the function
  echo "Hello, $name"
}

# Call
greet "Alice"
greet "Bob"

Return Values

Bash functions don't return values like most languages. return N sets the exit code (0–255). To pass data out, use stdout and capture with $().

get_timestamp() {
  date +"%Y-%m-%d %H:%M:%S"
}

log() {
  local level="$1"
  local message="$2"
  local ts
  ts=$(get_timestamp)
  echo "[$ts] [$level] $message"
}

log "INFO" "Script started"
log "ERROR" "Connection failed"

Return Status from Functions

file_exists() {
  [[ -f "$1" ]]  # exit code of [[ ]] becomes function's exit code
}

if file_exists "/etc/hosts"; then
  echo "File found"
fi

Always declare variables inside functions as local. Without local, you're writing to the global scope, causing subtle bugs when functions are called multiple times or in loops.

Up next

Bash local variables and scope explained

Sign in to track progress