Bash Function Libraries
A function library is a file that holds reusable functions. A script loads it with source, and its functions become available to the caller.
Create a library, then source it
The script writes a small library file first, then sources it. After sourcing, the greet function runs like any function in the script.
cat > greetlib.sh << 'EOF'
greet() {
echo "Hello, $1"
}
EOF
source greetlib.sh
greet "Sam"A guard stops the second load
The library returns at once when its flag is already set. The version stays 2 after the second source, proving the reset line never ran again.
cat > lib.sh << 'EOF'
if [ -n "${LIB_LOADED:-}" ]; then
return 0
fi
LIB_LOADED=1
lib_version=1
shout() {
echo "v$lib_version: $1"
}
EOF
source lib.sh
lib_version=2
source lib.sh
shout "ready"A clean library prints nothing at load time
Sourcing the library defines farewell but prints nothing. The only output comes from the explicit loaded line and the call itself.
cat > cleanlib.sh << 'EOF'
farewell() {
echo "Goodbye, $1"
}
EOF
source cleanlib.sh
echo "loaded"
farewell "Sam"Example
cat > toolib.sh << 'EOF'
if [ -n "${TOOLIB_LOADED:-}" ]; then
return 0
fi
TOOLIB_LOADED=1
shout() {
echo "${1^^}!"
}
repeat() {
echo "$1 $1"
}
EOF
source toolib.sh
source toolib.sh
shout "done"
repeat "go"Key points
- source: loads a file into the current shell, so its functions stay available.
- Dot command: the single dot . does the same job as source.
- Guard pattern: a flag variable that stops a library from loading twice.
- Double-sourcing: harmless for plain definitions, but it reruns any top-level code in the file.
- Side-effect rule: a library file should define functions only, and run nothing at load time.
- Library file: built inside this script with a quoted heredoc, so the case folder starts empty each run.
In this example, the script writes a library with a guard flag and two functions. It sources the library twice, and the guard skips the second load. Then it calls shout, which prints the word in capitals, and repeat, which prints its word twice.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does source do to a library file?