Reusable Bash Utility Functions

Su Suriya Ravichandran Updated 06 Dec 2026
13 min read ·Lesson 96 of 205

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 local for 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 ...) and if helper ...; then.
  • Send messages to standard error (lesson 56), so they never mix with data a caller captures.
  • Use return, not exit, so the caller decides what a failure means. The one exception is a function whose documented job is to end the script, such as die below.
  • 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:

  • log stores the level in a local variable and removes it from the argument list with shift (lesson 44). What remains is the message, which "$*" joins into one string with spaces.
  • printf builds the line in a fixed format and >&2 sends 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, warn and error pass 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.
  • die is the deliberate exception to "use return": 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_cmd checks 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 on PATH.
  • is_integer uses the =~ regular-expression test (lesson 69). The function has no return line: its status is the status of the last command, the [[ ]] test itself (lesson 90).
  • is_empty deletes 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 under set -u.
  • shift || true keeps a script that uses set -e from stopping when there was no item to shift (a failed shift returns 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 source did 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.
  • flaky is a function, and retry ran it like any other command. The global counter tries was updated because retry ran it in the current shell, not in a subshell.
  • The read -p prompt of confirm does 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_trim and so on, or use a separator such as utils::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 -F prints 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).

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Reusable Bash Utility Functions and get answers drawn from it.

Signed-in readers only.