Functions and argument parsing
Quick answer
Functions group reusable script operations; getopts handles short command-line options with a defined interface.
Prepare the practice environment
Run python3 lab-fixtures/shell-scripting/setup.py as an ordinary user from the extracted package root in a disposable Linux environment. Enter the printed directory, check pwd, then run export LC_ALL=C; umask 077; set -o pipefail. Use a fresh fixture for each example. Save the code as example.sh inside that directory and run bash --noprofile --norc -o pipefail example.sh rather than sourcing it. Stop if a command fails unexpectedly. All output paths must be new. The source of check-report.sh is in the fixture JSON. Outputs below are not commands.
How it works
Use name() { ...; } to define a function. Its positional arguments are local to the call; local declares a local variable inside it. return provides an exit status, while printf writes output. getopts reads options from positional parameters: in :o:, the leading colon selects quiet error handling and o: requires an argument. OPTARG holds the value; OPTIND points to the next argument. Reset OPTIND before a new independent parse. shift "$((OPTIND - 1))" drops processed arguments; the remainder can be filenames. This example accepts only short options, not GNU long options.
A function can print a useful message and still return a failure status, or return success without printing anything. Treat stdout as data and the return status as a separate outcome. With getopts, an unknown option and an option missing its required value are different errors in the leading-colon mode. After parsing, inspect the remaining argument count before reading a required filename. The delimiter -- can end option parsing when a filename starts with a dash.
Try the examples
report() { local path=$1 printf 'file: %s\n' "$path"}report 'daily report.txt'The helper receives one argument and prints a label.
Expected stdout:
file: daily report.txtcheck_file() { test -f "$1"; }if check_file absent.txt; then printf 'found\n'else printf 'missing\n'fiThe function returns the status of its last command.
Expected stdout:
missingset -- -o preview 'daily report.txt'mode=normalOPTIND=1while getopts ':o:' opt; do case $opt in o) mode=$OPTARG ;; :) printf 'missing option value\n' >&2; exit 2 ;; \?) printf 'unknown option\n' >&2; exit 2 ;; esacdoneshift "$((OPTIND - 1))"printf 'mode=%s\n' "$mode"for path in "$@"; do printf 'file=%s\n' "$path"; doneThe case statement selects the matching option or error. Remaining operands stay separate.
Expected stdout:
mode=previewfile=daily report.txtCommon mistakes
Do not use return to return arbitrary strings. Validate required arguments and reject unknown options before doing work.
Practice
Change the synthetic option list to -o without a value and then -z. Confirm a diagnostic and status 2 in both cases.
Related references
Study: bash, getopts. These are reference names, not deployed links.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functions and argument parsing — Knowledge Check
Apply the lesson concepts to the controlled shell fixture.
What does return provide?
What does local do inside a function?
What is OPTARG for?
What does shift after parsing do?