Bash Argument Parsing & CLI Design
Intermediatev1.0.0
Build user-friendly Bash CLI scripts — argument parsing with getopts, long options, help messages, input validation, and following Unix CLI conventions.
Content
Overview
Well-designed CLI scripts accept flags, options, and arguments following Unix conventions. Proper argument parsing makes scripts reusable, self-documenting, and user-friendly.
Why This Matters
- -Reusability — scripts with options are flexible for different use cases
- -Self-documenting — --help tells users what the script does
- -Unix conventions — users expect -v for verbose, -h for help
- -Automation — parseable arguments enable script composition
Step 1: Usage Function
Step 2: Parse Arguments
Step 3: Validate Arguments
Step 4: Use Parsed Arguments
Best Practices
- -Always provide
-h/--helpwith usage examples - -Use long options (
--verbose) for clarity, short (-v) for convenience - -Validate all inputs before executing
- -Use exit code 2 for usage errors (Unix convention)
- -Print errors to stderr (
>&2), data to stdout - -Include examples in the help message
- -Support
--to end option parsing (pass remaining as positional args)
Common Mistakes
- -No help message (users have to read the script)
- -Not validating argument values (garbage in, garbage out)
- -Using positional-only arguments for everything (hard to remember order)
- -Not handling unknown flags (silently ignored)
FAQ
Discussion
Loading comments...