0
0
Bash Scriptingscripting~5 mins

Function libraries (sourcing scripts) in Bash Scripting - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function libraries (sourcing scripts)
O(n)
Understanding Time Complexity

When using function libraries by sourcing scripts in bash, it is important to understand how the execution time grows as the size of the library increases.

We want to know how sourcing affects the script's running time as more functions are added.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


# source a library of functions
source my_functions.sh

# call a function from the library
my_function "argument"

# continue with script tasks

This code sources a file containing many functions, then calls one function from it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Reading and loading all lines of the sourced script once.
  • How many times: Exactly once per script execution, no loops or repeated traversals.
How Execution Grows With Input

As the size of the function library file grows, the time to read and load it grows proportionally.

Input Size (n)Approx. Operations
10 lines10 operations to read and load
100 lines100 operations to read and load
1000 lines1000 operations to read and load

Pattern observation: The time grows linearly as the library size increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to source the script grows directly with the number of lines or functions in the library.

Common Mistake

[X] Wrong: "Sourcing a script only loads the functions I call, so time does not grow with library size."

[OK] Correct: When sourcing, the entire file is read and parsed, even if only one function is used later.

Interview Connect

Understanding how sourcing affects script performance helps you write efficient bash scripts and shows you can reason about script behavior beyond just coding.

Self-Check

"What if the sourced script used lazy loading or conditional function definitions? How would the time complexity change?"