Design CLI input and output contracts
A command-line interface (CLI) is an agreement between a program and its callers: which arguments it accepts, where input comes from, what it prints and what its exit status means. Write the agreement before writing the parser. For a small greeting utility, require exactly one nonempty name, print one greeting to stdout and report misuse on stderr with status 2. Status 2 is our convention, not a universal rule. Keep machine-readable output stable and send progress messages to stderr; a caller may redirect or pipe stdout. If records may contain newlines, choose an explicit format or restrict the input; never claim an arbitrary text string is valid JSON. The examples invoke functions as stand-ins for a standalone script. In a real entry point, main "$@" as the final command propagates its status. A name containing an embedded newline is allowed by this simple nonempty-name contract and may yield multiple physical output lines. Do not treat this greeting as a one-line machine-readable record without an additional input restriction or encoding.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
A minimal contract
greet() { if (( $# != 1 )) || [[ -z $1 ]]; then printf 'usage: greet NAME\n' >&2 return 2 fi printf 'Hello, %s!\n' "$1"}greet 'Ada Lovelace' Expected stdout:
Hello, Ada Lovelace!The name remains one argument. The function succeeds with status 0.
Separate data and diagnostics
count_records() { printf 'counting records\n' >&2 printf '%s\n' "$#"}count_records red 'light blue' ''Expected stdout:
3Expected stderr:
counting recordsOnly the count appears on stdout. An explicitly empty argument counts as one.
Reject incorrect input
greet() { if (( $# != 1 )) || [[ -z $1 ]]; then printf 'usage: greet NAME\n' >&2 return 2 fi printf 'Hello, %s!\n' "$1"}greet ''status=$?printf 'status=%s\n' "$status"Expected stdout:
status=2Expected stderr:
usage: greet NAMENo greeting is printed; the parent records the function failure.
Common mistakes
Do not put a progress banner in stdout when a caller expects a single number. Do not treat no arguments as an empty argument; check $# before accessing $1.
Practice
Design a greeting contract with one required name. Test a name containing spaces, an empty argument and zero arguments. Verify stdout, stderr and status separately.
Next: Parse positional arguments with shift