Skip to content
CloudOps
Newsletter
All prompts
AI for Bash & Python Automation Difficulty: Intermediate ClaudeChatGPT

Bash getopts Long-Options Parser Prompt

Build a robust Bash option parser that supports both short flags and GNU-style long options with validation and a generated usage block

Target user
engineers who automate ops with Bash and Python
Difficulty
Intermediate
Tools
Claude, ChatGPT

The prompt

You are a senior automation engineer who has shipped dozens of production Bash CLIs and knows the exact boundaries of POSIX getopts versus hand-rolled long-option parsing.

I will provide:
- The list of options I need (short flag, long name, whether it takes a value, default, required/optional)
- The target shell and platform (e.g. bash 4.x on Ubuntu, or POSIX sh on Alpine)
- A short description of what the script does, for the help text

Your job:

1. **Choose the parsing strategy** — decide between `getopts` (short only) and a `while`/`case` loop that handles `--long`, `--long=value`, and `--` end-of-options; justify the choice for my target shell.
2. **Generate the parser** — emit a complete, copy-pasteable parser block with `set -euo pipefail`, clearly scoped variables, and no global leakage.
3. **Validate inputs** — reject unknown flags, missing required options, and missing values for value-taking flags, each with a distinct exit code and stderr message.
4. **Build the usage block** — produce a `usage()` function whose text is derived from the same option list, so help and parsing never drift apart.
5. **Add a self-test** — include 3-5 example invocations (valid and invalid) plus the expected exit code and output for each.

Output as: one fenced bash code block with the parser and usage function, followed by a short table of the example invocations and expected results.

Default to failing loudly on unknown or malformed options rather than silently ignoring them, and never let an unparsed flag fall through into positional arguments.
Newsletter

Free: the DevOps AI Incident-Triage Cheat Sheet

Subscribe and we’ll send you the one-page cheat sheet — plus weekly AI prompts, automation ideas, and tool reviews for infrastructure engineers. One email a week. No spam, unsubscribe anytime.

  • AI Incident-Triage Cheat Sheet (PDF)
  • Access to 1,603 DevOps AI prompts
  • One practical workflow email per week