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:
Syntax
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
#!/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 try C/C++/Java/PHP code in the editor
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
- Using a relative path for
source, so it breaks when the script is run from another directory. - Putting code that runs immediately inside the library file.
- Naming functions the same in different libraries, so one overrides the other.
🔒
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first:
- Function Basics
- The read Command and Here-Strings
- Function Arguments
- stdin, stdout, stderr and File Descriptors
- Return Values
- Redirection Operators
- Local Variables
- Pipes and Chaining Commands
- Recursive Functions
- Here-Documents (<<EOF)
- Function Libraries
- The tee Command
- Discarding Output with /dev/null