Reusable Bash Utility Functions
Most Bash scripts repeat the same small jobs: printing a status message, stopping with an error, checking that a command is installed, testing whether a value is a number, creating a folder, or retrying a command that sometimes fails. Writing these lines again in every script makes scripts longer and lets small differences creep in between them. A utility library solves this: the helpers are written once, in their own file, and every script loads them with source (lesson 95).
This lesson builds such a library, lib/utils.sh, one group of functions at a time, and then uses it from a script. Along the way it shows the rules that make a function safe to reuse in scripts you have not written yet.
What Makes a Function Reusable
A helper that lives in a shared file is called from many places, by scripts with different variables, options and expectations. To work everywhere, it should follow a few rules that earlier lessons introduced one by one:
- Use
localfor every variable the function needs (lesson 92), so it never overwrites a variable of the calling script. - Take input through arguments (
$1,$2,"$@", lesson 89), not through global variables that the caller has to set first. - Return data on standard output and report success with the status (lessons 90 and 91), so callers can write
x=$(helper ...)andif helper ...; then. - Send messages to standard error (lesson 56), so they never mix with data a caller captures.
- Use
return, notexit, so the caller decides what a failure means. The one exception is a function whose documented job is to end the script, such asdiebelow. - Quote every expansion (lesson 55), so file names and messages with spaces pass through unchanged.
The Library File and Its Include Guard
The library starts with a comment that says how to load it, followed by the include guard from lesson 95:
# utils.sh - reusable helper functions for Bash scripts.
# Load with: source "$SCRIPT_DIR/lib/utils.sh"
# Include guard: return at once if this file was already loaded.
[[ -n ${_UTILS_SH_LOADED:-} ]] && return 0
_UTILS_SH_LOADED=1
The guard variable uses the :- default (lesson 45), so the test also works in a script that runs with set -u, where reading an unset variable would otherwise stop the script. The leading underscore and the file-specific name keep it from clashing with the caller's own variables.
The file has no shebang line and is not meant to be executed. It only defines functions, so sourcing it has no visible effect until a function is called.
Message Functions
Logging is the most widely shared helper. One central log function formats every message, and short wrappers name the levels:
# timestamp: print the current date and time in one fixed format.
timestamp() {
date '+%Y-%m-%d %H:%M:%S'
}
# log LEVEL MESSAGE...: print a tagged message to standard error.
log() {
local level=$1
shift
printf '%s [%s] %s\n' "$(timestamp)" "$level" "$*" >&2
}
info() { log INFO "$@"; }
warn() { log WARN "$@"; }
error() { log ERROR "$@"; }
# die MESSAGE [STATUS]: print an error and end the script.
die() {
error "$1"
exit "${2:-1}"
}
How the pieces fit together:
logstores the level in a local variable and removes it from the argument list withshift(lesson 44). What remains is the message, which"$*"joins into one string with spaces.printfbuilds the line in a fixed format and>&2sends it to standard error. A script's output can therefore be redirected to a file or captured with$( )while the messages still appear on the terminal.info,warnanderrorpass all their arguments on with"$@", which keeps every argument intact.- Because the format lives in one place, changing it later (for example, adding the script name) changes every message of every script that uses the library.
dieis the deliberate exception to "usereturn": its whole purpose is to stop the script. The exit status defaults to 1 through${2:-1}, and the caller can pass another number.
Check Functions
Checks answer a yes-or-no question through their exit status, so they fit directly into if, && and ||:
# require_cmd NAME...: fail if any command is not installed.
require_cmd() {
local cmd missing=0
for cmd in "$@"; do
if ! command -v "$cmd" >/dev/null 2>&1; then
error "required command not found: $cmd"
missing=1
fi
done
return "$missing"
}
# is_integer VALUE: succeed if VALUE is a whole number (optional minus sign).
is_integer() {
[[ $1 =~ ^-?[0-9]+$ ]]
}
# is_empty VALUE: succeed if VALUE is empty or only whitespace.
is_empty() {
[[ -z ${1//[[:space:]]/} ]]
}
require_cmdchecks every name it is given before it returns, so a user who lacks two tools learns about both at once instead of fixing them one run at a time.command -v(lesson 72) finds builtins, functions and programs onPATH.is_integeruses the=~regular-expression test (lesson 69). The function has noreturnline: its status is the status of the last command, the[[ ]]test itself (lesson 90).is_emptydeletes every whitespace character with${1//pattern/}(lesson 54) and checks whether anything is left.
Text Functions
# trim TEXT: print TEXT without leading and trailing whitespace.
trim() {
local s=$1
s=${s#"${s%%[![:space:]]*}"}
s=${s%"${s##*[![:space:]]}"}
printf '%s\n' "$s"
}
# join_by SEPARATOR ITEM...: print the items joined by SEPARATOR.
join_by() {
local sep=$1
shift
local out=${1-}
shift || true
local item
for item in "$@"; do
out+=$sep$item
done
printf '%s\n' "$out"
}
trim is the same technique as the library in lesson 95. join_by takes the separator first, starts the result with the first item, and adds the separator in front of every further item, so no separator is left at either end. Two details make it robust:
${1-}gives an empty string when no item was passed, which matters underset -u.shift || truekeeps a script that usesset -efrom stopping when there was no item to shift (a failedshiftreturns status 1).
Both functions print their result with printf '%s\n' rather than echo, so a value such as -n is printed instead of being taken as an option (lesson 91).
File Functions
# ensure_dir PATH: create PATH (and parents) if missing.
ensure_dir() {
[[ -d $1 ]] && return 0
mkdir -p -- "$1" || { error "cannot create directory: $1"; return 1; }
}
# backup_file PATH: copy PATH to PATH.YYYYmmdd-HHMMSS.bak and print the new name.
backup_file() {
local src=$1 dest
[[ -f $src ]] || { error "not a regular file: $src"; return 1; }
dest="$src.$(date '+%Y%m%d-%H%M%S').bak"
cp -p -- "$src" "$dest" || return 1
printf '%s\n' "$dest"
}
ensure_dir returns at once when the folder already exists, so it can be called every time without checking first. The -- in mkdir -p -- and cp -p -- marks the end of options, so a path that begins with a dash is not taken for an option. backup_file follows the output-plus-status pattern: the new file name goes to standard output for the caller to capture, and the error message goes to standard error with status 1.
Control Functions
# retry COUNT DELAY COMMAND [ARGS...]: run COMMAND up to COUNT times.
retry() {
local count=$1 delay=$2 attempt=1
shift 2
until "$@"; do
if (( attempt >= count )); then
error "failed after $attempt attempts: $*"
return 1
fi
warn "attempt $attempt failed, retrying in ${delay}s: $*"
(( attempt++ ))
sleep "$delay"
done
}
# confirm PROMPT: ask a yes/no question; succeed only on y or yes.
confirm() {
local answer
read -r -p "$1 [y/N] " answer || return 1
[[ ${answer,,} == y || ${answer,,} == yes ]]
}
retry shows a powerful idea: a function can receive a whole command as its arguments. After shift 2 removes the count and the delay, "$@" is the command with its own arguments, and until "$@" runs it (lesson 81) until it succeeds or the attempts run out. Because the command runs inside the until condition, a failure does not trigger set -e.
confirm reads one answer, lowercases it with ${answer,,} and accepts only y or yes. Everything else, including an empty answer, means no. If there is no input at all (for example, in a script started by cron), read fails and the function returns 1, so a destructive action is never confirmed by accident.
Using the Library
A script finds the library relative to its own folder (lesson 95), loads it, and stops if the load fails:
#!/usr/bin/env bash
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
source "$SCRIPT_DIR/lib/utils.sh" || { echo "cannot load utils.sh" >&2; exit 1; }
info "starting"
require_cmd date cp && echo "tools present"
require_cmd date nosuchtool_xyz || echo "require_cmd status: $?"
for v in 42 -7 3.5 abc "" 007; do
if is_integer "$v"; then echo "[$v] integer"; else echo "[$v] not integer"; fi
done
is_empty " " && echo "blank is empty"
is_empty " x " || echo "' x ' is not empty"
echo "[$(trim " hello world ")]"
join_by , a b c
join_by " | " red green
join_by - only
echo "[$(join_by ,)]"
Output (the time stamps depend on when the script runs):
2026-11-21 20:53:08 [INFO] starting
tools present
2026-11-21 20:53:08 [ERROR] required command not found: nosuchtool_xyz
require_cmd status: 1
[42] integer
[-7] integer
[3.5] not integer
[abc] not integer
[] not integer
[007] integer
blank is empty
' x ' is not empty
[hello world]
a,b,c
red | green
only
[]
Note that 007 counts as an integer for is_integer: the test checks the characters, not the value. If the number will be used in arithmetic, remember that a leading zero means octal there, and 10#$v forces base 10 (lesson 49).
A Strict-Mode Script Using the Library
The library is written so it also works in a script with set -euo pipefail (lessons 119 to 121):
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
source "$SCRIPT_DIR/lib/utils.sh"
source "$SCRIPT_DIR/lib/utils.sh" # second load returns at once
echo "loaded once: $_UTILS_SH_LOADED"
ensure_dir "$SCRIPT_DIR/work/reports" && echo "dir ok"
ensure_dir "$SCRIPT_DIR/work/reports" && echo "dir ok again"
printf 'port=8080\n' > "$SCRIPT_DIR/work/app.conf"
copy=$(backup_file "$SCRIPT_DIR/work/app.conf")
echo "backup: ${copy##*/}"
backup_file "$SCRIPT_DIR/work/missing.conf" || echo "backup status: $?"
tries=0
flaky() { (( ++tries )); (( tries >= 3 )); }
retry 5 0 flaky && echo "flaky succeeded after $tries tries"
retry 2 0 false || echo "retry status: $?"
if confirm "Delete old reports?" <<< "Yes"; then echo "confirmed"; fi
if confirm "Delete old reports?" <<< "n"; then echo "confirmed"; else echo "not confirmed"; fi
if confirm "Delete old reports?" < /dev/null; then echo "confirmed"; else echo "no input: not confirmed"; fi
die "config missing" 3
echo "not reached"
Output, with the time stamps and the folder path shortened:
loaded once: 1
dir ok
dir ok again
backup: app.conf.20261121-205308.bak
2026-11-21 20:53:08 [ERROR] not a regular file: /home/ana/demo/work/missing.conf
backup status: 1
2026-11-21 20:53:08 [WARN] attempt 1 failed, retrying in 0s: flaky
2026-11-21 20:53:08 [WARN] attempt 2 failed, retrying in 0s: flaky
flaky succeeded after 3 tries
2026-11-21 20:53:08 [WARN] attempt 1 failed, retrying in 0s: false
2026-11-21 20:53:08 [ERROR] failed after 2 attempts: false
retry status: 1
confirmed
not confirmed
no input: not confirmed
2026-11-21 20:53:08 [ERROR] config missing
The script ended with status 3, the number passed to die, and the last echo never ran. A few things to notice:
- The second
sourcedid nothing because of the include guard. copy=$(backup_file ...)captured only the new file name. The error from the second call went to standard error and was not mixed into any captured value.flakyis a function, andretryran it like any other command. The global countertrieswas updated becauseretryran it in the current shell, not in a subshell.- The
read -pprompt ofconfirmdoes not appear in the output above because the answers came from a here string and/dev/null. Bash shows the prompt only when input comes from a terminal.
Running the same script with 2>/dev/null shows only standard output, which confirms the separation between data and messages:
loaded once: 1
dir ok
dir ok again
backup: app.conf.20261121-205308.bak
backup status: 1
flaky succeeded after 3 tries
retry status: 1
confirmed
not confirmed
no input: not confirmed
Name Clashes Between a Library and a Script
All functions in Bash share one global namespace. If a script defines a function with the same name as a library function, the definition that runs last wins, and every library function that calls it now calls the script's version:
#!/usr/bin/env bash
source ./lib/utils.sh
log() { echo "script's own log: $*"; }
info "hello"
script's own log: INFO hello
The script replaced log, and the library's info, which calls log, followed the replacement. Sometimes this is useful, because a script can change how all messages are printed. Usually it is an accident. Two habits reduce the risk:
- Prefix library names. Large libraries name their functions
utils_log,utils_trimand so on, or use a separator such asutils::log(Bash allows::in function names, while POSIX shells such as Dash do not). The prefix makes clashes unlikely and shows at the call site where a function comes from. - List what a library defines.
declare -Fprints every defined function name, which helps find a clash:
declare -F | awk '{print $3}'
For the library in this lesson, the list contains backup_file, confirm, die, ensure_dir, error, info, is_empty, is_integer, join_by, log, require_cmd, retry, timestamp, trim and warn.
Documenting Each Function
Every function in utils.sh begins with a one-line comment in the same shape: the name, its arguments in capitals with optional ones in brackets, and what it prints or returns. This is enough for a reader to use a function without reading its body:
# retry COUNT DELAY COMMAND [ARGS...]: run COMMAND up to COUNT times.
When a library grows, it is also worth recording which Bash features it needs. utils.sh uses [[ ]], =~, (( )), ${var,,}, local and read -p, so it needs Bash 4.0 or later (the ${var,,} lowercase expansion) and does not work when loaded with . in Dash or another sh. Lessons 188 and 189 cover writing helpers that also work in POSIX shells.
Growing the Library
A good utility library grows from real repetition: when the same few lines appear in a third script, they become a function in the library. Related functions can later be split into separate files, as in the lib/log.sh, lib/strings.sh and lib/files.sh layout of lesson 95, each with its own include guard. Later lessons add more candidates for such a library: a cleanup function registered with trap (lessons 123 and 124), argument parsing with getopts (lesson 130), lock files that stop a script from running twice (lesson 171), and helper functions that take arrays as arguments (lesson 104).