Script arguments and options
Parse a small option interface without losing a path containing spaces.
Arguments arrive as separate values
$# is the argument count, $1 the first argument and "$@" the complete list with its boundaries intact. shift removes the first argument. Check how many arguments are available before reading a required option value.
Bash’s getopts handles portable short options. A leading colon in its option string lets your script handle missing values and unsupported options itself. OPTARG contains an option argument and OPTIND identifies where ordinary positional arguments begin. Reset OPTIND if you call the same parser again in one shell.
Document the interface
A helpful tool has defaults, a help option and a consistent error status. An explicit -- terminates option parsing. Long GNU-style options are not automatically available from getopts; do not accidentally promise them.
Use a fixed printf format when repeating an argument. Never build an unquoted command string from the supplied path. This exercise accepts an output-directory label but only prints the proposed settings; later scripts use similarly parsed values to write reports.
output=reports
while getopts ':o:h' option; do
case "$option" in
o) output=$OPTARG ;;
h) printf 'Use -o DIRECTORY\n'; exit 0 ;;
*) printf 'Invalid option\n' >&2; exit 2 ;;
esac
done
printf 'output=%s\n' "$output"
Put it into practice.
Support `-o DIRECTORY` (default `reports`) and `-h`. Without -h, print `output=<directory>` and a newline. -h prints exactly `Usage: bash main.sh [-o DIRECTORY] [-h]` and exits 0. Unknown options, a missing -o value, or leftover positional arguments must print `Invalid arguments` to stderr and exit 2. Accept `--` as the end of options.
See an explained solution
output=reports
while getopts ':o:h' option; do
case "$option" in
o) output=$OPTARG ;;
h) printf 'Usage: bash main.sh [-o DIRECTORY] [-h]\n'; exit 0 ;;
*) printf 'Invalid arguments\n' >&2; exit 2 ;;
esac
done
shift "$((OPTIND - 1))"
if [ "$#" -ne 0 ]; then printf 'Invalid arguments\n' >&2; exit 2; fi
printf 'output=%s\n' "$output"
getopts performs option parsing without splitting the directory label. The post-parser argument check catches accidental extra input.