I built production-grade Bash using functions, getopts argument parsing, EXIT traps for cleanup, and arrays for structured data. Trap-based cleanup guaranteed temp files and locks were removed even when a script aborted mid-run.

Objective & Context

Robust automation needs argument parsing, guaranteed cleanup, and reuse. This lab adds getopts for flags, traps for deterministic teardown, functions for libraries, and arrays for lists, elevating the basics into maintainable tools used by the cron and sysadmin labs.

Environment & Prerequisites

  • Bash 5.x with shellcheck.
  • A task needing flags and temp files.
  • The strict-mode baseline from the basics lab.

Step-by-Step Execution

1. Parse flags with getopts

while getopts ":v:o:" opt; do
  case $opt in
    v) verbose=$OPTARG ;;
    o) out=$OPTARG ;;
    *) echo "usage: $0 -v N -o FILE" >&2; exit 2 ;;
  esac
done

2. Guarantee cleanup with a trap

tmp=$(mktemp); trap 'rm -f "$tmp"' EXIT

3. Iterate an array

hosts=(web1 web2 db1); for h in "${hosts[@]}"; do ssh "$h" uptime; done
web1: load average 0.12  web2: 0.08  db1: 0.31
(temp file removed on exit)

Validation & Testing

Abort the script mid-run (Ctrl-C) and confirm the trap still removes the temp file; pass invalid flags and confirm a clean usage error. Pass criteria: cleanup runs on every exit path and getopts rejects unknown options with exit 2.

Advanced: Troubleshooting
  • Leftover temp files: register the trap immediately after creating the resource.
  • Array word-splitting: always expand with "${arr[@]}" (quoted, @).
  • getopts misses long options: getopts handles short flags only; parse long flags manually.

Key Results

  • Guaranteed resource cleanup on all exit paths via EXIT traps.
  • Added robust flag parsing with getopts and usage errors.
  • Processed host lists safely with quoted array expansion.
  • Packaged reusable functions into a sourced library.