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

Function Libraries

In this page:

  1. Function Libraries

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)"

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.