Writing Readable and Maintainable Bash

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 163 of 205

A Bash script is read far more often than it is written. Someone opens it months later to find out why a backup failed, to add a new option, or to check whether it is safe to run on a new server, and that someone is often the original author, who no longer remembers how it works. Readable code lets that reader understand what the script does and why. Maintainable code lets them change it without breaking something else.

Shell scripts have a reputation for being hard to read because Bash allows very compact code: several commands on one line, single-letter variables, nested substitutions and unexplained flags. Compact code is not faster in any way that matters, and it hides bugs. This lesson shows a set of habits that make Bash scripts easy to read, review and change, and then applies them to a real script.

Understanding the Concept

Readability in a shell script comes from a few sources:

  • Structure. The reader can find the script's purpose, settings, helper functions and main logic in predictable places.
  • Names. Variables and functions say what they hold or do, so the code explains itself.
  • Small pieces. Each function does one job and can be understood, and tested, on its own.
  • Explicit behavior. Errors are reported clearly, options are parsed in one place, and nothing important depends on a side effect hidden three lines away.
  • Comments that explain why. The code shows what happens; comments record the reasons that the code cannot show.

These are not decorations added at the end. Each one also removes a class of bugs, as the complete example at the end of this lesson shows: the short, dense version of the script was not just harder to read, it was wrong.

A Predictable Layout

When every script follows the same order, a reader can find things without searching. A common layout is:

1. Shebang
2. Header comment: purpose, usage, inputs, outputs, exit status
3. Shell options (set -euo pipefail, shopt)
4. Constants and default settings
5. Small helper functions (usage, die, log)
6. Functions that do the real work
7. main function
8. main "$@"

The header comment is the most valuable part. It answers the first questions anyone has about the file:

#!/usr/bin/env bash
#
# user-report.sh - list regular user accounts and count them by login shell
#
# Usage: user-report.sh [-m MIN_UID] [PASSWD_FILE]
#   -m MIN_UID    lowest UID treated as a regular user (default: 1000)
#   PASSWD_FILE   file in /etc/passwd format (default: /etc/passwd)
#
# Output: one "user shell" line per regular account, then the number of
# accounts per shell. Exit status: 0 success, 1 unreadable file, 2 bad usage.

Calling a single main function from the last line (lesson 94) has two benefits. The reader sees the script's whole flow in one short function. And because everything above the last line only defines functions, nothing runs until Bash reaches main "$@"; a file that was only partly downloaded or is being replaced while it runs ends with a syntax error or does nothing, instead of running half of its commands.

Naming

Good names remove the need for most comments. Compare:

for l in $(cat $f); do u=$(echo $l | cut -d: -f1)
while IFS=: read -r name _password uid _gid _gecos _home shell; do

The second line documents the format of the file it reads. A widely used set of conventions for Bash:

KindConventionExamples
Constants and settings fixed at the topUPPER_CASE, often readonlyreadonly DEFAULT_MIN_UID=1000
Environment variables you export or readUPPER_CASEPATH, BACKUP_DIR
Ordinary variableslower_casepasswd_file, min_uid
Functionslower_case, a verb for actionscollect_users, print_shell_counts
Yes/no functionsa questionis_regular_user, has_free_space
Values you must accept but do not usea leading underscore_password, _gid

Keeping ordinary variables in lower case also avoids accidentally overwriting the shell's own upper-case variables, such as PATH, HOME, USER or IFS (lesson 35).

Avoid abbreviations that only you understand. cfg_dir is fine; cd2 is not. A slightly longer name costs nothing at run time.

Name the magic numbers

A bare number in a condition forces the reader to guess its meaning:

if [ $i -ge 1000 -a $i -ne 65534 ]; then

Give it a name, and the comment that explains it goes in one place:

readonly DEFAULT_MIN_UID=1000
readonly NOBODY_UID=65534   # "nobody" has a high UID but is not a person

Small Functions with One Job

A function that does one thing can be named after that thing, read in isolation and reused:

# is_regular_user UID: succeed for accounts that belong to people
is_regular_user() {
  local uid=$1
  (( uid >= min_uid && uid != NOBODY_UID ))
}

Guidelines that keep functions small and clear:

  • Declare variables with local (lesson 92), so a function does not silently change the caller's variables.
  • Name the parameters at the top: local uid=$1 is clearer than using $1 throughout the body.
  • Return status for yes/no questions (lesson 90) and print results for values (lesson 91). A function called is_... that prints true and returns 0 either way is a trap for the caller.
  • Write a one-line comment above any function whose name does not fully explain its arguments or output.
  • Keep option parsing in one function, so the rest of the script works with plain, already-validated variables.

Guard Clauses Instead of Deep Nesting

Deeply nested if blocks make the reader keep several conditions in mind at once. Handle the cases that stop processing first, then write the main path without nesting:

while IFS=: read -r name _password uid _gid _gecos _home shell; do
  [[ -n $name && $name != \#* ]] || continue   # skip blank and comment lines
  is_regular_user "$uid" || continue

  printf '%s %s\n' "$name" "$shell"
done < "$passwd_file"

The same pattern works at the start of functions ([[ -r $file ]] || die "cannot read $file") and scripts. Each guard line states one rule.

Long Commands

A long command on one line is hard to read and hard to compare in a version-control diff. Two ways to break it up:

Backslash continuation works, but it is fragile. A space after the backslash ends the command at that line, and the next line runs as a separate command. Here the first line of bs.sh ends with a backslash followed by a space (cat -A shows line ends as $):

printf "[%s] " one \ $
  two$
echo$
[one] [ ] bs.sh: line 2: two: command not found

The backslash escaped the space instead of the line ending, so printf received an argument consisting of one space, and two was run as a command.

An array has no such problem, allows a comment on each element, and keeps options as separate, correctly quoted words:

rsync_opts=(
  --archive
  --delete
  --exclude '*.tmp'   # temporary files are rebuilt on the server
)
rsync "${rsync_opts[@]}" "$src/" "$dest/"

With printf '[%s] ' in place of rsync, the arguments are:

[rsync] [--archive] [--delete] [--exclude] [*.tmp] [site/] [backup/]

Comments That Explain Why

A comment that repeats the code adds nothing and goes out of date when the code changes:

count=$((count + 1))   # add one to count

Useful comments record information the code cannot carry:

# Use the C locale so sort order is the same on every server.
# The --ignore-existing flag matters: the remote copy may be newer.
# Workaround: tool v2.3 exits 1 even on success when the list is empty.

Explain decisions, assumptions about the environment, units (seconds or milliseconds?), formats of input files, and why a check that looks unnecessary is actually needed. When you disable a ShellCheck rule (lesson 162), write why next to the directive.

Consistent Style

Consistency matters more than which style you choose. Pick one set of rules for a project and apply it everywhere:

  • Indent with two spaces (or four, or tabs, but always the same).
  • Put then and do on the same line as if, while and for: if [[ ... ]]; then.
  • Use $(...) rather than backticks, [[ ]] rather than [ ] in Bash scripts, and (( )) for arithmetic.
  • Quote every expansion unless you have a reason not to, and write that reason in a comment.
  • Prefer long, self-describing options in scripts (--archive rather than -a) where the command offers them.
  • Write error messages to standard error, prefixed with the script name (lesson 125).

Published style guides, such as the Google Shell Style Guide, make good starting points for a team. A formatter such as shfmt can apply indentation and spacing rules automatically, and ShellCheck catches risky patterns, so that code review can focus on what the script does.

Knowing When to Stop Using Bash

Readable code also means choosing the right language. Bash is excellent for gluing commands together, moving files and automating system tasks. It becomes hard to maintain when a script needs complex data structures, floating-point calculations, JSON or HTML parsing, or more than a few hundred lines of logic. At that point, a language such as Python is usually easier to read and test, and the Bash script can shrink to a short wrapper that calls it.

A Complete Example: Rewriting a Dense Script

The following script lists the regular user accounts in a file in /etc/passwd format and counts them by login shell. It works on simple input and is typical of scripts written in a hurry:

#!/bin/bash
f=${1:-/etc/passwd};declare -A c
[ -r $f ]||{ echo no file;exit 1;}
for l in $(cat $f);do u=$(echo $l|cut -d: -f1);i=$(echo $l|cut -d: -f3);s=$(echo $l|cut -d: -f7)
if [ $i -ge 1000 -a $i -ne 65534 ];then echo "$u $s";c[$s]=$((${c[$s]}+1));fi;done
for k in ${!c[@]};do echo "$k: ${c[$k]}";done

The test file users.txt contains seven accounts:

root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
ana:x:1000:1000:Ana Silva,,,:/home/ana:/bin/bash
raj:x:1001:1001::/home/raj:/bin/zsh
deploy:x:1002:1002:Deploy bot:/srv/deploy:/usr/sbin/nologin
lee:x:1003:1003:lee:/home/lee:/bin/bash

Running the dense version:

bash ur-v1.sh users.txt; echo "status $?"
ana 
ur-v1.sh: line 5: c: bad array subscript
ur-v1.sh: line 5: c[$s]: bad array subscript
status 0

The full-name field Ana Silva,,, contains a space. for l in $(cat $f) splits the file on spaces as well as newlines, so ana:x:1000:1000:Ana was processed as a line on its own, its seventh field was empty, and an empty key is not allowed in an array. The error stopped the loop, so three regular users were never reported, and the script still exited with status 0. Finding this bug in the dense version is hard, because seven separate ideas share one line.

The readable version:

#!/usr/bin/env bash
#
# user-report.sh - list regular user accounts and count them by login shell
#
# Usage: user-report.sh [-m MIN_UID] [PASSWD_FILE]
#   -m MIN_UID    lowest UID treated as a regular user (default: 1000)
#   PASSWD_FILE   file in /etc/passwd format (default: /etc/passwd)
#
# Output: one "user shell" line per regular account, then the number of
# accounts per shell. Exit status: 0 success, 1 unreadable file, 2 bad usage.

set -euo pipefail

readonly DEFAULT_PASSWD_FILE=/etc/passwd
readonly DEFAULT_MIN_UID=1000
readonly NOBODY_UID=65534   # "nobody" has a high UID but is not a person

min_uid=$DEFAULT_MIN_UID
passwd_file=$DEFAULT_PASSWD_FILE
declare -A shell_counts=()

usage() {
  echo "usage: ${0##*/} [-m MIN_UID] [PASSWD_FILE]" >&2
  exit 2
}

die() {
  echo "${0##*/}: $1" >&2
  exit 1
}

parse_args() {
  local opt
  while getopts ':m:' opt; do
    case $opt in
      m) min_uid=$OPTARG ;;
      *) usage ;;
    esac
  done
  shift $((OPTIND - 1))

  (( $# <= 1 )) || usage
  passwd_file=${1:-$DEFAULT_PASSWD_FILE}

  [[ $min_uid =~ ^[0-9]+$ ]] || usage
  [[ -r $passwd_file ]] || die "cannot read $passwd_file"
}

# is_regular_user UID: succeed for accounts that belong to people
is_regular_user() {
  local uid=$1
  (( uid >= min_uid && uid != NOBODY_UID ))
}

# Print "user shell" for each regular account and count accounts per shell.
collect_users() {
  local name _password uid _gid _gecos _home shell
  while IFS=: read -r name _password uid _gid _gecos _home shell; do
    [[ -n $name && $name != \#* ]] || continue   # skip blank and comment lines
    is_regular_user "$uid" || continue

    printf '%s %s\n' "$name" "$shell"
    shell_counts[$shell]=$(( ${shell_counts[$shell]:-0} + 1 ))
  done < "$passwd_file"
}

print_shell_counts() {
  local shell
  echo "--"
  for shell in "${!shell_counts[@]}"; do
    printf '%s: %d\n' "$shell" "${shell_counts[$shell]}"
  done | sort
}

main() {
  parse_args "$@"
  collect_users
  print_shell_counts
}

main "$@"

How It Works

  • The header states the purpose, the options, the output format and the exit statuses, so a reader can use the script without reading its code.
  • Settings at the top. The default file, the minimum UID and the nobody UID are named constants. Changing the policy means changing one clearly labeled line.
  • parse_args is the only place that looks at the command line. It uses getopts (lesson 130), validates that -m is a number and that the file is readable, and leaves the rest of the script two plain variables, min_uid and passwd_file.
  • is_regular_user turns the UID rule into a question with a readable name.
  • collect_users reads the file line by line with while IFS=: read -r (lesson 114), naming all seven fields. Lines are never split on spaces, so full names with spaces are handled. Two guard lines skip blank lines, comments and non-regular accounts. The count uses ${shell_counts[$shell]:-0} so the first account for a shell starts from zero; the shorter (( shell_counts[$shell]++ )) would return status 1 for the first increment and stop the script under set -e (lesson 119).
  • print_shell_counts prints a separator and the counts, sorted so the output is the same on every run; the order of keys in an associative array is not defined (lesson 103).
  • main shows the whole flow in three lines.

The readable version is longer: 81 lines against 6. Almost all of the extra lines are the header, blank lines, names and checks. None of them make the script slower in any noticeable way, and every one of them answers a question a future reader would otherwise have to work out.

Running the Complete Example

bash user-report.sh users.txt; echo "status $?"
ana /bin/bash
raj /bin/zsh
deploy /usr/sbin/nologin
lee /bin/bash
--
/bin/bash: 2
/bin/zsh: 1
/usr/sbin/nologin: 1
status 0

All four regular accounts are reported, nobody is excluded by the named rule, and the counts are sorted. The option and the error paths behave as the header promises:

bash user-report.sh -m 1002 users.txt; echo "status $?"
bash user-report.sh -m abc users.txt; echo "status $?"
bash user-report.sh missing.txt; echo "status $?"
bash user-report.sh a b; echo "status $?"
deploy /usr/sbin/nologin
lee /bin/bash
--
/bin/bash: 1
/usr/sbin/nologin: 1
status 0
usage: user-report.sh [-m MIN_UID] [PASSWD_FILE]
status 2
user-report.sh: cannot read missing.txt
status 1
usage: user-report.sh [-m MIN_UID] [PASSWD_FILE]
status 2

Adding a feature to this version, for example an option to exclude accounts whose shell is nologin, means adding one line to parse_args and one guard line to collect_users. In the dense version, the same change would mean editing the middle of an 82-character line that already holds an if, an assignment and the end of the loop.

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 Writing Readable and Maintainable Bash and get answers drawn from it.

Signed-in readers only.