← Back to Bash Course | Chapter 8: Input/Output & Redirection | Lesson 11 of 13

Function Libraries

A function library is like a toolbox you keep in the garage: you put your favorite tools in one file and then borrow that whole box from any other script.

In this page:

  1. Function Libraries
Syntax
bash
source library_file.sh
function_from_library arguments

Function Libraries

Related functions can be grouped into a separate .sh file and loaded into another script with source file.sh (or the shorthand . file.sh), making them reusable across multiple scripts.

This is Bash's equivalent of importing a module. Sourcing runs the file in the current shell, so its functions and variables become directly available.

Note: source lib.sh and . lib.sh are equivalent — the dot is just a shorter alias for source.

Example: Function Libraries

bash
#!/bin/bash
# Simulating a sourced library inline for this example
square() {
    echo $(( $1 * $1 ))
}

cube() {
    echo $(( $1 * $1 * $1 ))
}

echo "Square of 4: $(square 4)"
echo "Cube of 3: $(cube 3)"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using a relative path for source, so it breaks when the script is run from another directory.
  2. Putting code that runs immediately inside the library file.
  3. Naming functions the same in different libraries, so one overrides the other.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.