Bash Script Structure
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:
- 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.
- 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:
$0holds the name the script was started with, such as./backup_notes.shor/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 givestool.shfrom/home/user/bin/tool.sh.readonlymarks a variable as fixed, so a later line cannot change it by mistake.$(date +%Y-%m-%d)runs thedatecommand 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.