0PricingLogin
Linux Command Line & Bash Scripting Mastery · Lesson

Building and Sourcing Reusable Bash Libraries

Organize shared helpers into sourceable .sh library files with include guards and namespaced function prefixes.

What Is a Bash Library?

In software engineering, a library is a collection of reusable functions that multiple programs can share. Bash supports the same concept through sourceable shell scripts.

Instead of copy-pasting helper functions into every script, you place them in a dedicated .sh file and load it with the source command (or its shorthand .). Any functions, variables, or aliases defined in that file become available in the calling script's current shell session.

  • Promotes the DRY principle (Don't Repeat Yourself)
  • Centralises bug fixes — fix once, all callers benefit
  • Makes individual scripts shorter and easier to read
  • Enables team-wide consistency in logging, error handling, and utility logic

A well-structured Bash project typically has a lib/ directory containing these shared files, mirroring the conventions of higher-level languages.

The source Command and the Dot Operator

There are two equivalent ways to load a library file into the current shell environment:

  • source /path/to/lib.sh — the explicit, readable form
  • . /path/to/lib.sh — the POSIX-compatible shorthand

Both execute the file in the current shell process, not a subshell, so every function and variable defined inside it becomes part of your script's environment immediately after the call.

A common pattern is to locate the library relative to the calling script using $BASH_SOURCE, which makes the project portable regardless of where it is installed.

#!/usr/bin/env bash
# main.sh — load a library relative to this script's own location

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/lib/utils.sh"

echo "Library loaded. Calling greet..."
greet "World"

All lessons in this course

  1. Designing Functions with Local Scope and Return Codes
  2. Building and Sourcing Reusable Bash Libraries
  3. Parsing Flags and Arguments with getopts
  4. Passing Arrays and Associative Maps Between Functions
← Back to Linux Command Line & Bash Scripting Mastery