Organizing Scripts into Functions

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 94 of 205

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:

  • usage prints 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.
  • die prints 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 call exit, because its whole job is to stop the program (lesson 90 explained the difference between return and exit).
  • log prints a message unless quiet mode is on. Every function that wants to report progress calls log, so the -q option works everywhere without each function checking QUIET itself.

Work functions. Each one does one task:

  • parse_args reads the command-line arguments and sets QUIET and DIR. It receives the script's arguments because main passes them on with "$@" (lesson 89).
  • check_dir stops the script with a clear message if the argument is not a folder.
  • count_matches prints 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_file handles one file: it collects both counts in local variables, prints a formatted line through log, 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_cleanup is 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:

DirectionChannelLesson
Data into the functionArguments, $1, $2, "$@"89
Success or failure outreturn status90
Result data outPrinted output, captured with $( )91
Working variableslocal92
Deliberately shared stateA few clearly named globals93

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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Organizing Scripts into Functions and get answers drawn from it.

Signed-in readers only.