9. Functions and Modularity#
This chapter shows how Bash functions make scripts easier to reuse, test, debug, and organize into maintainable pieces.
Functions: Package related commands behind a reusable name.
Parameters: Pass values into functions without relying on global state.
Scope: Use local variables to avoid accidental interference.
Status and output: Return success or failure through exit status and data through stdout.
Libraries: Source shared function files to keep larger scripts modular.
Chapter Video
What are Functions in Bash (8:34) by Microsoft Developer
Hosted on YouTube; property of its original creator, embedded here for educational reference only.
Learning Objectives
By the end of this chapter, you will be able to:
Define and invoke Bash functions.
Distinguish local and global variable scope.
Use return statuses and output intentionally.
Organize reusable functions into script libraries.
Chapter Flow
Glossary
# |
Term |
Explanation |
|---|---|---|
1 |
Function |
A named block of commands that can be invoked repeatedly. |
2 |
Function call |
An invocation of a function by name. |
3 |
Parameter |
A value passed into a function or script. |
4 |
Local variable |
A variable visible only within a function when declared with |
5 |
Global variable |
A variable visible broadly in the current shell context. |
6 |
Scope |
The region of code where a variable name has meaning. |
7 |
Return status |
The numeric success or failure result produced by a function. |
8 |
Stdout return value |
Data emitted with |
9 |
|
A Bash command that exits a function with a status code. |
10 |
|
A command that reads another file into the current shell. |
11 |
Function library |
A file containing reusable function definitions. |
12 |
Recursion |
A function calling itself. |
13 |
|
All positional parameters preserved as separate words when quoted. |
14 |
|
All positional parameters joined according to shell rules. |
15 |
Encapsulation |
Keeping implementation details inside a function or library boundary. |
16 |
Namespace |
A naming convention that avoids collisions between functions or variables. |
17 |
Side effect |
A change a function makes outside its direct output or status. |
18 |
Guard clause |
An early check that exits a function when required conditions are not met. |
19 |
Modularity |
Organizing a script into focused reusable parts. |
20 |
Call stack |
The chain of active function calls at a point in execution. |