Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 25 min · revision 3

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

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 POSIX test command 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 $status is empty, evaluating [ $status = "active" ] expands to [ = "active" ]. test then sees an equal sign with no left operand, prints [: =: unary operator expected and returns status 2, which an if treats 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 -a and -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, -ge or arithmetic evaluation blocks: if (( count > 10 )); then ... fi.
  • String Comparisons: Use = (equality) and != (inequality). Inside [[ ]], Bash also accepts ==; inside [ ] use =, because POSIX test has no == and Dash rejects it ([: a: unexpected operator). Lexicographical string sorting with < and > requires double brackets: [[ $a < $b ]].
  • String Tests: -z is true for an empty string and -n for 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:

  1. 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 $file set to the literal text /var/log/*.log. Guard the body with [ -e "$file" ] || continue, or run shopt -s nullglob before the loop so an unmatched pattern expands to nothing.

  2. 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 ... done loop:

    • 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), read returns non-zero for it but still fills line, so this test processes that final line instead of silently dropping it.
Bash · control-flow.sh: a case statement, functions and a while read loop
#!/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 $?"
Terminal
bash control-flow.sh
Expected output
Config entry: port=8080
Daemon status: healthy
Usage: control-flow.sh {start|stop|status}
handle_action returned 2

The 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

Practice check · 3 questions

Conditionals, while read loops, and function scoping check

Three questions on read loops, local variables and case.

Q1. `hosts.txt` was written with `printf 'web\ndb\ncache'`, so its last line has no newline. What does `while IFS= read -r h; do echo "up: $h"; done < hosts.txt; echo "after loop: $h"` print?
Q2. A helper `backup_db()` assigns `retries=3`, and the main loop also uses `retries`. After a call to `backup_db`, the main loop misbehaves. What is the fix?
Q3. In a Bash `case` statement, what ends a pattern's commands so that execution does not continue into the next pattern?
Practice only: not graded, not saved, not evidence.

05. Apply it

Adopt these control flow standards across all production automation:

  • Prefer Arithmetic Blocks for Numbers: Write if (( retry_count < max_retries )); then instead 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 use find ... -print0 | while IFS= read -r -d '' f; do for recursive trees.
  • Enforce Case Statements for Subcommands: When building operational CLI wrappers, structure arguments using case "$1" in to 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.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check