Function Libraries
In this page:
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
🔒
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