home / skills / a5c-ai / babysitter / getopts-parser-generator

This skill generates robust getopts-based argument parsing for shell scripts, supporting short and long options, validation, and helpful usage text.

npx playbooks add skill a5c-ai/babysitter --skill getopts-parser-generator

Review the files below or copy the command above to add this skill to your agents.

Files (2)
SKILL.md
2.8 KB
---
name: getopts-parser-generator
description: Generate getopts-based argument parsing for shell scripts with short/long options and validation.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
---

# Getopts Parser Generator

Generate getopts-based argument parsing for shell scripts.

## Capabilities

- Generate getopts parsing code
- Support short and long options
- Implement option validation
- Create help text generation
- Handle required arguments
- Generate usage documentation

## Usage

Invoke this skill when you need to:
- Add argument parsing to shell scripts
- Support short and long options
- Validate argument values
- Generate help text

## Generated Patterns

### Getopts with Long Options

```bash
#!/usr/bin/env bash

# Default values
VERBOSE=false
OUTPUT=""
FORMAT="text"
FORCE=false

# Usage function
usage() {
    cat <<EOF
Usage: $(basename "$0") [OPTIONS] <input>

Options:
    -h, --help              Show this help
    -v, --verbose           Enable verbose output
    -o, --output FILE       Output file (default: stdout)
    -f, --format FORMAT     Output format: text, json, csv (default: text)
    -F, --force             Force overwrite existing files

Arguments:
    input                   Input file to process
EOF
}

# Parse options
parse_options() {
    # Transform long options to short ones
    for arg in "$@"; do
        shift
        case "$arg" in
            '--help')    set -- "$@" '-h' ;;
            '--verbose') set -- "$@" '-v' ;;
            '--output')  set -- "$@" '-o' ;;
            '--format')  set -- "$@" '-f' ;;
            '--force')   set -- "$@" '-F' ;;
            *)           set -- "$@" "$arg" ;;
        esac
    done

    # Parse short options
    local OPTIND opt
    while getopts ":hvo:f:F" opt; do
        case "$opt" in
            h) usage; exit 0 ;;
            v) VERBOSE=true ;;
            o) OUTPUT="$OPTARG" ;;
            f)
                case "$OPTARG" in
                    text|json|csv) FORMAT="$OPTARG" ;;
                    *) die "Invalid format: $OPTARG" ;;
                esac
                ;;
            F) FORCE=true ;;
            :) die "Option -$OPTARG requires an argument" ;;
            \?) die "Unknown option: -$OPTARG" ;;
        esac
    done

    shift $((OPTIND - 1))

    # Remaining arguments
    if [[ $# -lt 1 ]]; then
        usage
        die "Missing required argument: input"
    fi

    INPUT="$1"
    shift

    # Extra arguments
    EXTRA_ARGS=("$@")
}

die() {
    echo "Error: $*" >&2
    exit 1
}

# Parse and validate
parse_options "$@"

# Validation
[[ -f "$INPUT" ]] || die "Input file not found: $INPUT"
[[ -n "$OUTPUT" && -f "$OUTPUT" && "$FORCE" != true ]] && \
    die "Output file exists: $OUTPUT (use --force to overwrite)"
```

## Target Processes

- shell-script-development
- shell-completion-scripts
- argument-parser-setup

Overview

This skill generates getopts-based argument parsing code for shell scripts that supports both short and long options, validation, and help text generation. It produces robust parsing patterns including required-argument handling, default values, and usage documentation. The output is ready to paste into bash scripts and includes common validation checks and error handling.

How this skill works

The skill transforms long options into short equivalents, then emits a getopts loop that handles option flags, option arguments, and validation branches. It generates a usage function, default variable initialization, error reporting helper, and post-parse checks for required positional arguments and file checks. The produced code includes examples of value validation (enumerations, existence checks) and overwrite protection for output files.

When to use it

  • Adding argument parsing to an existing shell script that lacks flags or validation
  • Standardizing CLI behavior across multiple scripts with consistent help and error messages
  • Needing both short (-v) and long (--verbose) option support in bash without external libraries
  • Enforcing validation rules like allowed values, required files, or mutually exclusive flags
  • Generating usage documentation and examples automatically for a script

Best practices

  • Initialize default values at the top of the script to make behavior explicit
  • Include a usage() function and call it on invalid input or when -h/--help is requested
  • Transform long options to short ones before calling getopts to keep parsing portable
  • Validate option values (enumerations, numeric ranges, file existence) immediately after parsing
  • Use a die() helper for consistent error output and non-zero exit codes

Example use cases

  • A build script that accepts --target, --output, and --verbose with validation of allowed targets
  • A deploy tool that requires a positional environment argument and checks for a credentials file
  • A data conversion script that supports --format (text|json|csv) and prevents accidental overwrites
  • Quickly scaffolding CLI parsing for utilities in CI pipelines to standardize logs and errors

FAQ

Does the generator support both short and long options?

Yes. It maps long options to short ones before running getopts so you get both forms without non-portable parsers.

Can it validate option values like specific strings or file existence?

Yes. Generated code includes validation branches for enumerated values and common filesystem checks such as file existence and overwrite protection.