Organizing Scripts into Functions
A short Bash script is often written as a list of commands from top to bottom. As a script grows, that list becomes hard to read, hard to change and hard to test, because every line depends on everything that ran before it. Organizing a script into functions means splitting the work into named, self-contained pieces, and ending the file with a single call to a main function that runs those pieces in order.
This lesson brings together what lessons 88 to 93 introduced (defining functions, arguments, status codes, output, local variables and scope) and shows how they shape a complete, well-structured script.
Why Structure a Script with Functions
Functions give a script the same advantages they give programs in any language:
- Names explain intent. A line such as
check_dir "$DIR"says what happens; the five lines inside the function say how. - Each piece can be read alone. A function with its own arguments and local variables can be understood without reading the rest of the script.
- Code is written once. Logic that is needed in several places, such as printing an error and stopping, lives in one function.
- Changes stay contained. Fixing how files are counted means editing one function, not hunting through the whole file.
- Pieces can be tested and reused. A function can be called from a test, or loaded into another script with
source(lesson 95).
The Layout of an Organized Script
A common layout, from top to bottom:
1. Shebang line and a comment describing the script and its usage
2. Settings and constants (readonly values, default options)
3. Helper functions (usage, error reporting, logging)
4. Work functions (the actual tasks)
5. The main function, which calls the others in order
6. A single line that starts everything: main "$@"
Only the last line does anything when the file is read. Everything above it either sets a value or defines a function.
A Complete Example
The following script counts ERROR and WARN lines in every .log file of a folder. It is small, but it has all the parts of the layout:
#!/usr/bin/env bash
#
# logreport.sh - count ERROR and WARN lines in the .log files of a folder.
# Usage: logreport.sh [-q] DIRECTORY
# ---- settings and constants --------------------------------------------
readonly SCRIPT_NAME=${0##*/}
readonly E_USAGE=2
readonly E_NODIR=3
QUIET=0
# ---- helper functions ---------------------------------------------------
usage() {
cat <<USAGE
Usage: $SCRIPT_NAME [-q] DIRECTORY
Count ERROR and WARN lines in every .log file of DIRECTORY.
-q print only the total line
USAGE
}
die() {
local code=$1
shift
echo "$SCRIPT_NAME: $*" >&2
exit "$code"
}
log() {
(( QUIET )) || echo "$*"
}
# ---- work functions -----------------------------------------------------
parse_args() {
if [[ $1 == -q ]]; then
QUIET=1
shift
fi
(( $# == 1 )) || { usage >&2; exit "$E_USAGE"; }
DIR=$1
}
check_dir() {
[[ -d $1 ]] || die "$E_NODIR" "not a directory: $1"
}
count_matches() {
local pattern=$1 file=$2
grep -c -- "$pattern" "$file"
}
report_file() {
local file=$1 errors warns
errors=$(count_matches ERROR "$file")
warns=$(count_matches WARN "$file")
log "$(printf '%-10s errors=%d warns=%d' "${file##*/}" "$errors" "$warns")"
TOTAL_ERRORS=$(( TOTAL_ERRORS + errors ))
}
# ---- main ---------------------------------------------------------------
main() {
parse_args "$@"
check_dir "$DIR"
local file
TOTAL_ERRORS=0
for file in "$DIR"/*.log; do
[[ -e $file ]] || continue
report_file "$file"
done
echo "total errors: $TOTAL_ERRORS"
}
main "$@"
The test folder logs held three files: app.log with two ERROR lines and one WARN line among five lines, sys.log with one WARN line among two lines, and an empty empty.log. Running the script in different ways:
$ bash logreport.sh logs
app.log errors=2 warns=1
empty.log errors=0 warns=0
sys.log errors=0 warns=1
total errors: 2
$ bash logreport.sh -q logs
total errors: 2
$ bash logreport.sh
Usage: logreport.sh [-q] DIRECTORY
Count ERROR and WARN lines in every .log file of DIRECTORY.
-q print only the total line
$ bash logreport.sh nope
logreport.sh: not a directory: nope
The exit statuses were 0, 0, 2 and 3.
Understanding the Example
Settings and constants. SCRIPT_NAME holds the file name of the script without its directory (${0##*/}, lesson 54), so messages name the script correctly however it is called. The exit codes E_USAGE and E_NODIR are named, read-only constants (lessons 40 and 90), so the code says exit "$E_USAGE" instead of a bare number. QUIET is a global setting with a default value; written in capitals, it stands out as a value that several functions share.
Helper functions. These are small, general tools that the rest of the script relies on:
usageprints the help text with a here document (lesson 63). Keeping it in one function means the help text exists in exactly one place, ready to be printed for--help(lesson 131) or after a usage error.dieprints an error message to standard error and ends the script with a given status. It is one of the few functions that is allowed to callexit, because its whole job is to stop the program (lesson 90 explained the difference betweenreturnandexit).logprints a message unless quiet mode is on. Every function that wants to report progress callslog, so the-qoption works everywhere without each function checkingQUIETitself.
Work functions. Each one does one task:
parse_argsreads the command-line arguments and setsQUIETandDIR. It receives the script's arguments becausemainpasses them on with"$@"(lesson 89).check_dirstops the script with a clear message if the argument is not a folder.count_matchesprints a count, so callers capture it with$( )(lesson 91). It uses--so that a pattern starting with a dash is not taken as an option.report_filehandles one file: it collects both counts in local variables, prints a formatted line throughlog, and adds to the shared total.
The main function. main reads like a description of the program: parse the arguments, check the folder, report each log file, print the total. Its loop variable file is declared local (lesson 92). The check [[ -e $file ]] || continue handles a folder with no .log files, where the pattern stays unexpanded (lesson 82).
The last line. main "$@" passes all of the script's arguments, unchanged, to main.
Why main Is Called at the End
Two properties of Bash make the final main "$@" line important.
A function must be defined before it is called (lesson 88). Bash reads a script one command at a time and runs each command as soon as it has read it. If a script calls a function on line 1 and defines it on line 2, the call fails:
greet
greet() { echo "hello"; }
order2.sh: line 1: greet: command not found
With all code inside functions and the only call on the last line, every function is defined by the time main runs. Inside the functions, the order no longer matters: main can call greet even if greet is written below main, because both exist before the call happens:
main() { greet; }
greet() { echo "hello from greet"; }
main "$@"
hello from greet
This lets you put main near the top of the file, right after the helpers, if you prefer to read the overview first, as long as the call main "$@" stays at the very end.
Nothing runs until the whole file has been read. Compare two versions of a broken script whose last lines are missing (for example, because a download was cut off or an edit was not finished). The flat version runs its first commands before Bash discovers the problem:
echo "step 1: deleting old reports"
echo "step 2: building new report"
if [ -d /tmp ]; then
echo "step 3"
step 1: deleting old reports
step 2: building new report
flat.sh: line 5: syntax error: unexpected end of file
The version organized into functions defines everything first, so the syntax error is found while Bash is still reading the definitions, and no step runs:
step1() { echo "step 1: deleting old reports"; }
step2() { echo "step 2: building new report"; }
main() {
step1
step2
if [ -d /tmp ]; then
echo "step 3"
}
main "$@"
withmain.sh: line 8: syntax error near unexpected token `}'
withmain.sh: line 8: `}'
Both scripts ended with status 2. For a script whose first steps delete or change files, the difference between "half the work was done" and "nothing was done" matters.
Passing the Arguments On Correctly
The final line must be written as main "$@", with the quotes. Lesson 89 showed that "$@" keeps every argument as it was given, while an unquoted $@ splits arguments that contain spaces:
print_args() { printf '[%s] ' "$@"; echo; }
main() { print_args "$@"; }
main "$@"
main $@
Called as bash script.sh "a b" c:
[a b] [c]
[a] [b] [c]
The quoted form gives main the two original arguments; the unquoted form gives it three.
Deciding What Becomes a Function
There is no fixed rule, but these questions help:
- Can you name it? If a block of lines can be described by a short verb phrase (
check_dir,report_file,parse_args), it is a good candidate for a function with that name. - Does it appear more than once? Repeated code belongs in one function that is called from each place.
- Does it do one thing? A function called
check_and_report_and_cleanupis a sign that it should be three functions. - Does it fit on one screen? A function that is hard to see in one view is usually doing several jobs.
Every function should also have a clear contract with its callers:
| Direction | Channel | Lesson |
|---|---|---|
| Data into the function | Arguments, $1, $2, "$@" | 89 |
| Success or failure out | return status | 90 |
| Result data out | Printed output, captured with $( ) | 91 |
| Working variables | local | 92 |
| Deliberately shared state | A few clearly named globals | 93 |
In logreport.sh, only QUIET, DIR and TOTAL_ERRORS are global, and each is set by one function and read by others on purpose. Everything else is local or passed as an argument.
Making a Script Usable as a Library
A script organized into functions can also serve as a library: another script can load its functions with source (lesson 95) and call them. The problem is that sourcing the file would also run its final main "$@". Bash can tell the two situations apart. BASH_SOURCE[0] is the path of the file currently being read, and $0 is the name of the script that was started. They are equal only when the file is run directly:
greet() { echo "hello, $1"; }
main() { greet "${1:-world}"; }
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
main "$@"
fi
Running the file directly runs main:
$ bash guard.sh Ana
hello, Ana
Sourcing it from another script only defines the functions, and the caller can use them:
source ./guard.sh
echo "main did not run; calling greet:"
greet Ravi
main did not run; calling greet:
hello, Ravi
Where Settings and Strict Mode Go
Options that should apply to the whole script, such as the strict-mode settings set -euo pipefail covered in lessons 119 to 121, or a trap that cleans up temporary files (lessons 123 and 124), usually go near the top, right after the constants, so they are active before main starts. Global settings that main will change, like QUIET above, get their default values in the same section, so a reader can see every global variable of the script in one place.
Portability
The layout itself works in any POSIX shell: functions, a main function and a final main "$@" line behave the same in Dash. The example script uses Bash features such as [[ ]] and the (( )) command, so it needs Bash, which its #!/usr/bin/env bash line requests (lesson 26). The library guard uses BASH_SOURCE, which only Bash provides. Lessons 188 and 189 show how to write the same structure for sh.