Before this lesson, complete bash-functions, bash-conditionals, bash-loops-arrays.
This course runs GNU Bash with ordinary GNU text tools in a fresh Linux sandbox.
A command-line interface needs an input grammar just as a file format does. Specify which options take values, whether options may repeat, how unknown options fail, and what ends option parsing. This lab accepts leading --prefix VALUE options, then positional names. Once the first positional name appears, the remaining arguments are data. An explicit -- also switches permanently to positional input.
Apply the contract
A while loop with case makes each transition visible. Consume two arguments for an option plus its value and one for the separator. Check the available count before reading the value; a supplied empty value still counts as present. Shift the separator away before leaving the loop, or it becomes an unintended name. Treat unknown leading options as usage errors and write the fixed diagnostic to stderr with status two.
args=(--prefix report -- '-n' 'two words')
printf 'arguments=%s\n' "${#args[@]}"
printf '<%s>\n' "${args[@]}"Reason about the edge cases
Keep parsing separate from rendering. The parser selects a prefix and leaves the remaining positional parameters intact; the renderer forwards their exact string contents. Repeating --prefix replaces the prior prefix, which is an explicit policy rather than an accident. For single-letter option grammars Bash getopts is often preferable, while this small long-option parser matches the lab contract. Tests cover empty labels, a leading-dash name after --, missing values and repeated options. A successful-looking output line cannot compensate for the wrong exit status or a diagnostic sent to the wrong stream.
Practice
Implement labels: consume leading --prefix VALUE options (later ones replace earlier ones), then positional names. -- ends option parsing, so names after it can start with dashes. The default prefix is item; an explicitly empty prefix is valid. Print PREFIX:NAME for each name. Unknown leading options or a missing prefix value produce only the documented usage line on stderr and exit 2. Successful calls exit 0, including no names. Once the first positional name appears, all remaining arguments are names.
Run sample starts again from the first public fixture and grants no mastery evidence. Submit checks all fixtures, including edge cases. Read the specification before editing; the bug and fill phases share the build’s contract. Flashcards reinforce recall on a separate schedule.