Bash Script Structure

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 24 of 205

A Bash script is a text file of commands that Bash runs from top to bottom. A script of three lines needs no planning, but once it grows to thirty or three hundred lines, a clear structure is what keeps it readable and safe to change. Experienced script writers arrange their files in the same order every time: an interpreter line, a header comment, settings, constants, functions, and finally a small entry point that starts the work. This lesson walks through each part using one complete script.

Understanding the Concept

When you run a script, Bash reads it line by line and runs each command as soon as it reaches it. Two consequences shape the whole structure:

  1. A function must be defined before it is called. Bash learns about a function when it reads the definition, so a call that appears earlier in the file fails.
  2. Everything that is not inside a function runs immediately, in the order it is written.

Good structure uses these rules. All definitions come first, and the only commands that run at the top level are the last few lines that start the program.

A Complete Example

The following script, backup_notes.sh, copies a folder into a dated backup folder. Read it once as a whole, then each part is explained below.

#!/usr/bin/env bash
# backup_notes.sh - copy a notes folder into a dated backup folder.
# Usage: ./backup_notes.sh SOURCE_DIR DEST_DIR

set -u

SCRIPT_NAME=${0##*/}
readonly DATE_STAMP=$(date +%Y-%m-%d)

usage() {
  echo "Usage: $SCRIPT_NAME SOURCE_DIR DEST_DIR" >&2
}

backup() {
  local source_dir=$1
  local dest_dir=$2/notes-$DATE_STAMP

  mkdir -p "$dest_dir"
  cp -r "$source_dir"/. "$dest_dir"/
  echo "Backed up $source_dir to $dest_dir"
}

main() {
  if [ "$#" -ne 2 ]; then
    usage
    exit 1
  fi

  if [ ! -d "$1" ]; then
    echo "$SCRIPT_NAME: $1 is not a directory" >&2
    exit 2
  fi

  backup "$1" "$2"
}

main "$@"

A notes folder holding a.txt and b.txt gives the following result when the script is run (the script has been made executable, which a later lesson explains):

./backup_notes.sh notes backups

Output (the date is the day of the run):

Backed up notes to backups/notes-2026-11-20

The backup folder now contains both files:

backups/notes-2026-11-20/a.txt
backups/notes-2026-11-20/b.txt

The Parts of a Script

The Shebang Line

#!/usr/bin/env bash

The first line of a script is called the shebang (from "hash" and "bang", the names of # and !). When you run the file directly, the operating system reads this line to learn which program should interpret the rest. The line #!/usr/bin/env bash asks the env program to find bash in your PATH, which works on systems where Bash is installed in different places. A dedicated lesson covers the shebang in detail. For now, remember two rules: it must be the very first line, and it must start with exactly #!.

The Header Comment

# backup_notes.sh - copy a notes folder into a dated backup folder.
# Usage: ./backup_notes.sh SOURCE_DIR DEST_DIR

Anything after a # is a comment. Bash ignores it, but people read it. A good header states the script's name, its purpose and how to call it, so that anyone who opens the file understands it without reading the code.

Shell Settings

set -u

The set command changes how Bash behaves. The option -u makes Bash stop with an error when the script reads a variable that was never given a value. Without it, a misspelled variable name silently becomes an empty string, which can turn a command like rm -r "$DIR/" into a request to delete from the root. Later lessons on error handling cover set -e and set -o pipefail as well.

Constants and Variables

SCRIPT_NAME=${0##*/}
readonly DATE_STAMP=$(date +%Y-%m-%d)

Settings that are used in several places belong near the top, where they are easy to find and change. There are four new pieces of syntax here:

  • $0 holds the name the script was started with, such as ./backup_notes.sh or /home/user/bin/backup_notes.sh.
  • ${0##*/} removes the longest part of the value that ends with a slash, which leaves only the file name. For a path stored in a variable, the same idea gives tool.sh from /home/user/bin/tool.sh.
  • readonly marks a variable as fixed, so a later line cannot change it by mistake.
  • $(date +%Y-%m-%d) runs the date command and inserts its output. This is called command substitution.

Functions

usage() {
  echo "Usage: $SCRIPT_NAME SOURCE_DIR DEST_DIR" >&2
}

A function groups commands under a name, and calling that name runs them. The definition has the form name() { commands; }. In this function, >&2 sends the message to standard error instead of standard output. Messages meant for the person who ran the script, such as usage text and errors, belong on standard error so that they do not mix with the script's real output when that output is redirected or piped.

backup() {
  local source_dir=$1
  local dest_dir=$2/notes-$DATE_STAMP
  ...
}

Inside a function, $1 and $2 are the function's own arguments, not the script's. The local keyword creates variables that exist only inside the function, so they cannot overwrite a variable with the same name elsewhere. Giving the arguments readable names such as source_dir also makes the commands below easier to follow than a bare $1.

The commands of backup do the actual work: mkdir -p creates the destination and any missing parent folders without complaint if it already exists, and cp -r "$source_dir"/. "$dest_dir"/ copies everything inside the source folder, including hidden files, into the new folder.

The main Function and Its Call

main() {
  ...
}

main "$@"

Putting the script's control flow into a main function is a convention borrowed from other languages. It keeps the logic in one named place and makes sure that the file has only one top-level command that does anything. The last line calls it with "$@", which expands to all of the script's arguments with each one kept separate, even when an argument contains spaces. Always write "$@" with the quotes.

Inside main, the check [ "$#" -ne 2 ] compares the argument count in $# with the number 2, and [ ! -d "$1" ] tests that the first argument is not a directory.

Exit Status

A script reports the outcome of its run with an exit status: a number from 0 to 255 that the caller can read. By convention 0 means success and anything else means failure. The exit command ends the script with a status, and a script with no explicit exit returns the status of its last command.

Choosing different numbers for different failures lets callers react to the cause. In this script 1 means wrong usage and 2 means a bad directory. Here are both failures:

./backup_notes.sh
echo "status=$?"
./backup_notes.sh nope backups
echo "status=$?"

Output:

Usage: backup_notes.sh SOURCE_DIR DEST_DIR
status=1
backup_notes.sh: nope is not a directory
status=2

The variable $? holds the exit status of the last command, so echo "status=$?" has to come immediately after the command you are checking. The messages above come from usage and from the echo ... >&2 line. A terminal shows standard error and standard output together, so you see them in the order they were written.

Checking the Syntax Without Running

The -n option reads the script and reports syntax errors without running any command:

bash -n backup_notes.sh
echo "syntax status=$?"

Output:

syntax status=0

A status of 0 with no message means that Bash found nothing wrong with the syntax. It cannot tell you whether the script behaves correctly, only that it is well-formed. It is a cheap check to run before you execute a script that deletes or overwrites files.

Why Order Matters

The functions in the example are defined before main "$@". Suppose a script calls main on line 2 and defines it on line 3:

#!/usr/bin/env bash
main "$@"
main() { echo "in main"; }

Running it prints:

./early.sh: line 2: main: command not found

Bash had not yet read the definition when it reached the call. Inside a function body, however, you may call another function that is defined later in the file, as long as the definition has been read by the time the function actually runs. This script works, because both definitions are read before the last line calls main:

#!/usr/bin/env bash
main() { helper; }
helper() { echo "helper ran"; }
main

Output:

helper ran

That is why main in the larger example can call usage and backup regardless of the order in which they appear.

Practical Applications

A short script that follows the same layout, with a settings block, one function and an entry point:

#!/usr/bin/env bash
# disk_report.sh - print the size of each folder given on the command line.

set -u

report() {
  local dir=$1
  du -sh "$dir"
}

main() {
  for dir in "$@"; do
    report "$dir"
  done
}

main "$@"

Called with two folders, the script runs du -sh once for each (the sizes depend on your files):

./disk_report.sh notes backups

Output:

12K	notes
16K	backups

Keeping this layout from the very first script means that adding features later is a matter of adding a function, not of rearranging the file. It also means that you can read any script written this way in the same order: header, settings, helpers, then main.

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 Bash Script Structure and get answers drawn from it.

Signed-in readers only.