0
0
Bash Scriptingscripting~5 mins

Function libraries (sourcing scripts) in Bash Scripting

Choose your learning style9 modes available
Introduction

Function libraries let you keep useful commands in one place. You can reuse them in many scripts without rewriting.

You want to share common functions across multiple bash scripts.
You need to organize your code to keep scripts clean and simple.
You want to update a function once and have all scripts use the new version.
You are working on a big project with many scripts that use the same helpers.
Syntax
Bash Scripting
source /path/to/library.sh
# or
. /path/to/library.sh

source or . runs the library script in the current shell.

Functions and variables from the library become available in your script.

Examples
This example shows a simple library with a function hello. The main script loads it and calls the function.
Bash Scripting
# library.sh
hello() {
  echo "Hello from library!"
}

# main.sh
source ./library.sh
hello
Using . to source a utility script with an add function that sums two numbers.
Bash Scripting
# utils.sh
add() {
  echo "$(( $1 + $2 ))"
}

# script.sh
. ./utils.sh
add 3 5
Sample Program

This program has a library script with a function say_goodbye. The main script loads it and calls the function to print a message.

Bash Scripting
# library.sh
say_goodbye() {
  echo "Goodbye!"
}

# main_script.sh
#!/bin/bash
source ./library.sh
say_goodbye
OutputSuccess
Important Notes

Make sure the path to the library script is correct when sourcing.

Sourcing runs the script in the current shell, so variables and functions stay available.

Use chmod +x only if you want to run the library script directly, but sourcing does not require execute permission.

Summary

Function libraries help reuse code by sharing functions across scripts.

Use source or . to load a library script into your current script.

This keeps your scripts clean and easy to maintain.