Writing Readable and Maintainable Bash
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:
| Kind | Convention | Examples |
|---|---|---|
| Constants and settings fixed at the top | UPPER_CASE, often readonly | readonly DEFAULT_MIN_UID=1000 |
| Environment variables you export or read | UPPER_CASE | PATH, BACKUP_DIR |
| Ordinary variables | lower_case | passwd_file, min_uid |
| Functions | lower_case, a verb for actions | collect_users, print_shell_counts |
| Yes/no functions | a question | is_regular_user, has_free_space |
| Values you must accept but do not use | a 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=$1is clearer than using$1throughout the body. - Return status for yes/no questions (lesson 90) and print results for values (lesson 91). A function called
is_...that printstrueand 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
thenanddoon the same line asif,whileandfor: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 (
--archiverather 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
nobodyUID are named constants. Changing the policy means changing one clearly labeled line. parse_argsis the only place that looks at the command line. It usesgetopts(lesson 130), validates that-mis a number and that the file is readable, and leaves the rest of the script two plain variables,min_uidandpasswd_file.is_regular_userturns the UID rule into a question with a readable name.collect_usersreads the file line by line withwhile 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 underset -e(lesson 119).print_shell_countsprints 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).mainshows 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.