Functions
A function is a named group of commands. Functions keep scripts readable ("backup_database" says more than 15 lines of commands), let you reuse code, and make scripts much easier to test and change.
Defining and calling
greet() {
echo "Hello, $1!"
}
greet Asha
greet "Ravi Kumar"Hello, Asha! Hello, Ravi Kumar!
- Define it with
name() { … }before you call it (Bash reads scripts top to bottom). - Call it like any command: name, then arguments. No parentheses when calling.
- Inside, the arguments are
$1,$2,$#and"$@", just like a script's.
Local variables
Variables in Bash are global by default, even inside functions. That causes surprising bugs:
count=10
bump() {
count=99 # oops: changes the global
local temp=5 # only exists inside the function
echo "inside: count=$count temp=$temp"
}
bump
echo "outside: count=$count temp=[$temp]"inside: count=99 temp=5 outside: count=99 temp=[]
💡 Declare every variable inside a function with
local. It's the single best habit for bug-free functions.
Returning values
Functions have two ways to send something back:
- An exit code with
return N(0–255): for success or failure. - Output: anything the function prints, which the caller captures with
$( ).
is_even() {
(( $1 % 2 == 0 )) # the exit code of the last command is returned
}
square() {
echo $(( $1 * $1 ))
}
for n in 3 4; do
if is_even "$n"; then echo "$n is even"; else echo "$n is odd"; fi
done
result=$(square 12)
echo "12 squared is $result"3 is odd 4 is even 12 squared is 144
return is for status, not data: return 300 wraps around to 44, and you can't return text. Print the data and capture it instead.
Because the output is the return value, functions that return data must send messages to stderr so they don't end up in the result:
get_version() {
echo "reading version…" >&2
echo "2.4.1"
}
v=$(get_version)
echo "version is [$v]"reading version… version is [2.4.1]
Validating arguments
create_user() {
local name=$1 role=${2:-viewer}
if [[ -z $name ]]; then
echo "create_user: a name is required" >&2
return 1
fi
echo "created $name with role $role"
}
create_user asha admin
create_user ravi
create_user || echo "failed with exit code $?"created asha with role admin created ravi with role viewer create_user: a name is required failed with exit code 1
Passing arrays and lists
Pass several values with "$@", and loop over them inside:
backup_all() {
local dest=$1
shift # the rest of the arguments are files
local file
for file in "$@"; do
echo "copy '$file' → $dest/"
done
echo "$# files queued"
}
files=("notes.txt" "my photo.jpg" "data.csv")
backup_all /mnt/backup "${files[@]}"copy 'notes.txt' → /mnt/backup/ copy 'my photo.jpg' → /mnt/backup/ copy 'data.csv' → /mnt/backup/ 3 files queued
(Arrays are covered properly in the next lesson.)
A script built from functions
Larger scripts follow one pattern: helpers at the top, the work in small functions, and a main function at the bottom that ties them together.
#!/usr/bin/env bash
set -euo pipefail
log() { printf '[%s] %s\n' "$(date -u +%H:%M:%S)" "$*" >&2; }
die() { log "ERROR: $*"; exit 1; }
check_branch() {
local branch=$1
[[ $branch == main || $branch == release-* ]] || die "refusing to deploy branch '$branch'"
log "branch $branch is deployable"
}
build() {
log "building…"
mkdir -p dist && echo "<h1>shop</h1>" > dist/index.html
}
upload() {
local target=$1
log "uploading $(find dist -type f | wc -l) file(s) to $target"
}
main() {
local branch=${1:?usage: deploy.sh BRANCH [TARGET]}
local target=${2:-staging}
check_branch "$branch"
build
upload "$target"
log "done"
}
main "$@"bash deploy.sh main production 2>&1 | sed 's/^\[[0-9:]*\]/[time]/'
echo "---"
bash deploy.sh feature-x 2>&1 | sed 's/^\[[0-9:]*\]/[time]/'[time] branch main is deployable [time] building… [time] uploading 1 file(s) to production [time] done --- [time] ERROR: refusing to deploy branch 'feature-x'
(The sed replaces the real timestamps with [time] so the output above stays the same each run.)
loganddieare tiny helpers you'll copy into almost every script.main "$@"at the end passes the script's arguments tomain, so the whole script reads top to bottom like a table of contents.set -euo pipefailstops the script on errors. It's explained in Error handling and debugging.
Libraries with source
Put shared functions in a file and load them into any script with source:
# lib.sh: shared helpers
log() { echo "[log] $*"; }
require() { command -v "$1" > /dev/null || { echo "missing: $1" >&2; return 1; }; }source ./lib.sh
log "lib loaded"
require bash && log "bash is installed"
require kubectl || log "install kubectl first"[log] lib loaded [log] bash is installed missing: kubectl [log] install kubectl first
command -v name is the reliable way to check whether a program is installed.
Functions in your terminal
Functions in ~/.bashrc become your own commands. A favourite:
mkcd() { mkdir -p -- "$1" && cd -- "$1"; }
mkcd projects/new-app
pwd/home/you/projects/new-app
An alias can't do this, because aliases can't take arguments in the middle of a command. Functions can.
Practice
- Write
max A Bthat prints the larger of two numbers. - Write
is_file_older PATH DAYSthat returns success if the file was last changed more thanDAYSdays ago (hint:find "$1" -mtime +"$2"). - Restructure one of your earlier scripts into functions with a
main. - Write
confirm "question"that asks[y/N]and returns 0 only foryoryes. Use it asif confirm "Continue?"; then ….
1.How do you call a function greet with the argument Asha?
2.A function needs to give back the text "2.4.1". How?
3.Why use local inside functions?