Control flow you will actually use: tests, case, loops, functions, read and command substitution
Master robust Bash control flow: test brackets versus double brackets, case statements, whitespace-safe while read loops, local function scopes, and command substitution.
Contentsand lesson path
On this page
- Conditional Evaluation: [ vs [[ and Numeric vs String Comparisons
- Loops: Whitespace-Safe File Iteration and while read Idioms
- Modular Shell Design: Local Scopes and Command Substitution
- Check your understanding
- Apply it
- Review prompt
Lessons of Scripting Basics
- Anatomy of a script: shebang, arguments and exit codes Concept · 15 min
- Control flow you will actually use: tests, case, loops, functions, read and command substitution Worked example · 25 min
- Quoting, strict mode, tracing with set -x and failing loudly Worked example · 20 min
- Lab: an idempotent backup job with logging and a schedule Lab · 30 min
- Beyond Bash: jq, yq and porting a script to Python Worked example · 25 min
- Check: review and repair a fragile script Knowledge check · 8 questions
What you will learn
- Write a Bash script that takes arguments, validates input, uses variables, conditionals, loops and functions, and returns meaningful exit codes.
Prerequisites: Linux CLI
01. Conditional Evaluation: [ vs [[ and Numeric vs String Comparisons
Tests are where many shell bugs start. Bash offers two conditional constructs that look alike but are parsed in different ways:
-
Single Brackets (
[ ... ]): Single brackets are the POSIXtestcommand under another name. In Bash and Dash it is a shell builtin (type [prints[ is a shell builtin), and a standalone/usr/bin/[also exists. Because[is parsed like any ordinary command, all normal shell word splitting and pathname globbing expansions occur on arguments inside the brackets. If an unquoted variable$statusis empty, evaluating[ $status = "active" ]expands to[ = "active" ].testthen sees an equal sign with no left operand, prints[: =: unary operator expectedand returns status 2, which aniftreats as false. Furthermore,<and>inside[ ... ]are not comparisons: the shell treats them as redirections.>quietly creates an empty file named after the right-hand operand, and<tries to read from such a file. -
Double Brackets (
[[ ... ]]): Double brackets represent a first-class compound shell keyword in Bash, Ksh, and Zsh. Because the shell parser treats[[ ... ]]as special syntax rather than a standard command, word splitting and filename globbing are automatically suppressed inside the brackets. An unquoted empty variable[[ $status == "active" ]]evaluates safely without throwing syntax errors. Moreover, double brackets support natural logical operators (&&and||instead of-aand-o), glob pattern matching ([[ $filename == *.tar.gz ]]), and POSIX extended regular expressions via the=~operator ([[ $version =~ ^v[0-9]+.[0-9]+ ]]). Note that in modern Bash, regular expressions on the right-hand side of=~must NOT be enclosed in quotes; quoting the pattern causes Bash to interpret the regex characters as literal text.
Choose the operator by the kind of value you compare:
- Numeric Comparisons: Must use
-eq,-ne,-lt,-le,-gt,-geor arithmetic evaluation blocks:if (( count > 10 )); then ... fi. - String Comparisons: Use
=(equality) and!=(inequality). Inside[[ ]], Bash also accepts==; inside[ ]use=, because POSIXtesthas no==and Dash rejects it ([: a: unexpected operator). Lexicographical string sorting with<and>requires double brackets:[[ $a < $b ]]. - String Tests:
-zis true for an empty string and-nfor a non-empty one. - File Tests: Common file test operators include
-f(regular file exists),-d(directory exists),-s(file exists and size is greater than zero bytes), and-e(path exists on disk).
02. Loops: Whitespace-Safe File Iteration and while read Idioms
Iterating over files, directory structures, and text streams requires strict adherence to whitespace-safe patterns. A dangerous anti-pattern common among engineers is iterating over filenames using for file in $(ls *.log). If any filename contains a space (such as access 2026.log), the shell splits the name into two separate tokens (access and 2026.log), executing subsequent commands on non-existent file paths.
Two safe iteration idioms cover most cases:
-
Direct Shell Globbing:
for file in /var/log/*.log; do ... done. The shell expands globs directly into an array of discrete file words, preserving internal spaces as long as"$file"is enclosed in double quotes inside the loop body. One catch: if nothing matches, Bash leaves the pattern unchanged, so the loop runs once with$fileset to the literal text/var/log/*.log. Guard the body with[ -e "$file" ] || continue, or runshopt -s nullglobbefore the loop so an unmatched pattern expands to nothing. -
Stream Line-by-Line Reading: When reading a text file or pipeline output line by line, use the canonical
while IFS= read -r line || [ -n "${line}" ]; do ... doneloop:IFS=: Clearing the Internal Field Separator (IFS=) prevents the shell from trimming leading and trailing whitespace from the line contents.-r: Disables backslash escape interpretation, ensuring that paths containing backslashes (such as Windows shares or regex expressions) are read verbatim without character loss.|| [ -n "${line}" ]: If the last line of a file has no trailing newline (common in files written by some editors and tools),readreturns non-zero for it but still fillsline, so this test processes that final line instead of silently dropping it.
#!/usr/bin/env bash
set -euo pipefail
# Subcommand routing using case statement
handle_action() {
local action="${1:-}"
case "${action}" in
start)
echo "Starting application daemon..."
;;
stop)
echo "Stopping application daemon..."
;;
status)
echo "Daemon status: healthy"
;;
*)
echo "Usage: $0 {start|stop|status}" >&2
return 2
;;
esac
}
# Parse config file line-by-line safely
parse_config() {
local config_file="$1"
local line
while IFS= read -r line || [ -n "${line}" ]; do
# Skip empty lines and comment lines
[[ "${line}" =~ ^[[:space:]]*# ]] && continue
[[ -z "${line}" ]] && continue
echo "Config entry: ${line}"
done < "${config_file}"
}
# Try both functions on a three-line file whose last line has no newline
printf '# app settings\n\nport=8080' > app.conf
parse_config app.conf
handle_action status
handle_action restart || echo "handle_action returned $?"bash control-flow.shConfig entry: port=8080
Daemon status: healthy
Usage: control-flow.sh {start|stop|status}
handle_action returned 2The comment line and the empty line are skipped, and port=8080 is printed although the file ends without a newline. $0 in the usage line is the path you used to start the script. return 2 gives the caller a status to test; under set -e, the || echo is what keeps the script running after that failure.
03. Modular Shell Design: Local Scopes and Command Substitution
By default, all variables in Bash have global scope across the entire process lifetime. If a helper function assigns retries=3, it silently overwrites any variable named retries in the caller shell context. Functions should declare internal variables with the local keyword. Declare first and assign on the next line (local timestamp then timestamp=$(date +%s)): in the one-line form local timestamp=$(date +%s) the exit status is that of local, which succeeds, so a failing command substitution is silently ignored even under set -e (ShellCheck SC2155). Variables that leak out of functions are a common source of bugs that are hard to trace.
Return Values vs. Output Capture: In Bash, the return statement can only transmit an exit status code (an 8-bit integer from 0 to 255). To return complex data like strings, lists, or JSON payloads from a function, write the data to standard output and capture it at the call site using modern command substitution ($(command)). Avoid legacy backtick syntax (`command`), which makes nested substitutions and quote escaping fragile and error-prone.
When evaluating subcommands, remember that command substitution runs in a separate forked subshell process. Any modifications to environment variables or shell working directories performed inside $(cd /tmp && pwd) do not persist in the parent shell environment.
04. Check your understanding
05. Apply it
Adopt these control flow standards across all production automation:
- Prefer Arithmetic Blocks for Numbers: Write
if (( retry_count < max_retries )); theninstead of[ "$retry_count" -lt "$max_retries" ]for clearer, typo-resistant numeric comparisons. - Always Use local in Functions: Treat untagged global variables inside functions as critical code review defects. Declare every temporary variable with
local. - Never Parse ls Output: Never write
for f in $(ls). Always iterate directly over shell globs (for f in /var/log/*.log; do) or usefind ... -print0 | while IFS= read -r -d '' f; dofor recursive trees. - Enforce Case Statements for Subcommands: When building operational CLI wrappers, structure arguments using
case "$1" into handle subcommands cleanly with default*)usage fallbacks.
06. Review prompt
Contrast [ ... ] and [[ ... ]] in Bash, detailing why single brackets fail when evaluating unquoted variables or using redirection operators. Explain the necessity of IFS= and -r in while read loops. Describe how local variable declarations protect state in large shell scripts.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.