[![Actions Status](https://github.com/tecolicom/getoptlong/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/tecolicom/getoptlong/actions?workflow=test) [![MetaCPAN Release](https://badge.fury.io/pl/Getopt-Long-Bash.svg)](https://metacpan.org/release/Getopt-Long-Bash) # NAME getoptlong - Option parsing that does what you mean, for Bash # SYNOPSIS **Option definition:** declare -A OPTS=( [&USAGE]="command [options] file..." [verbose |v+ # Verbosity ]=0 [output |o: # Output file ]=/dev/stdout [config |c? # Config file ]= [include |I@ # Include paths ]= [define |D% # Definitions ]= [count |n:=i # Count integer ]=1 [mode |m:=(^(fast|slow)$) # Mode ]=fast ) **One-liner:** . getoptlong.sh OPTS "$@" **Multi-step:** . getoptlong.sh - getoptlong init OPTS getoptlong parse "$@" && eval "$(getoptlong set)" **Or:** eval "$(getoptlong OPTS)" # VERSION 0.5.0 # DESCRIPTION **getoptlong.sh** is a Bash library providing Perl's [Getopt::Long](https://metacpan.org/pod/Getopt%3A%3ALong)-style option parsing. Options are defined in a Bash associative array: the key specifies the option name, aliases, type, and other attributes; the value sets the default. The library parses command-line arguments, sets variables, and leaves non-option arguments in `$@`. Two usage modes are available: **one-liner** for simple scripts (source with array name and arguments), and **multi-step** for advanced control (separate init, parse, and set calls). Supports short (`-v`) and long (`--verbose`) options with bundling (`-vvv`). **Option types**: _flag_, _required argument_, _optional argument_, _array_, _hash_, _callback_. **Validation**: _integer_, _float_, _regex_. **Help message** generation. **Pass-through** for wrapper scripts. **Multiple invocations** for subcommand support. For a gentle introduction, see [Getopt::Long::Bash::Tutorial](https://metacpan.org/pod/Getopt%3A%3ALong%3A%3ABash%3A%3ATutorial). # INSTALLATION cpanm -n Getopt::Long::Bash # USAGE ## One-liner Source with array name and arguments to parse in one step: . getoptlong.sh OPTS "$@" Configuration parameters must be included in the options array (e.g., `[&PREFIX]=OPT_`). Callback registration is not available in this mode; use `!` modifier for automatic callback instead. ## Multi-step Source the library first, then call init, parse, and set separately: . getoptlong.sh - getoptlong init OPTS getoptlong parse "$@" && eval "$(getoptlong set)" This mode allows callback registration between init and parse. **Note:** When sourcing without arguments (`. getoptlong.sh`), the current shell's positional parameters are passed to the library. If the first argument happens to match an existing associative array name, it may cause unexpected behavior. Use `. getoptlong.sh -` to safely source without side effects. # OPTION DEFINITION Options are defined as elements of an associative array. Each key specifies the option's name, type, and modifiers, while the value provides the default. Whitespace is allowed anywhere in the definition for readability. Configuration parameters can also be included with `&` prefix (e.g., `[&PREFIX]=OPT_`); see ["CONFIGURATION"](#configuration). The key format is: [NAME[|ALIAS...][TYPE[MOD]][DEST][=VALIDATE] # DESC]=DEFAULT ## COMPONENTS - **NAME** Long option name (`--name`). Hyphens become underscores in variables (`--dry-run` → `$dry_run`). - **ALIAS** Additional names separated by `|` (e.g., `verbose|v|V`). - **TYPE** Argument type specifier: (none) or + Flag (counter) : Required argument ? Optional argument @ Array (multiple values) % Hash (key=value pairs) - **MOD (MODIFIER)** Special behavior flags (can be combined): ! Callback - calls function when option is parsed > Pass-through - collects option and value into array - **DEST** Custom variable name (e.g., `[opt|o:MYVAR]` stores in `$MYVAR`). - **VALIDATE** Value validation: `=i` (integer), `=f` (float), `=`. See ["VALIDATION"](#validation). - **DESC (DESCRIPTION)** Help message text (everything after `#`). # OPTION TYPES Each option type determines how arguments are handled and stored. ## FLAG (`+` or none) A flag takes no argument. First use sets to `1`, subsequent uses increment (useful for verbosity levels). Use `--no-X` to reset to empty string. Bundling supported: `-vvv` equals `-v -v -v`. [verbose|v]= # $verbose: 1 when specified [debug|d+]=0 # $debug: increments (-d -d -d or -ddd) Numeric initial value (like `0`) enables counter display in help. ## REQUIRED ARGUMENT (`:`) The option requires an argument; error if missing. Use `--no-X` to reset to empty string (useful for disabling defaults). [output|o:]= # --output=file, --output file, -ofile, -o file Short form `-o=value` is **not** supported (use `-ovalue` or `-o value`). ## OPTIONAL ARGUMENT (`?`) The argument is optional. The variable has three possible states: a value (`--config=file`), empty string (`--config` without value), or unset (option not specified). Use `[[ -v config ]]` to check if the option was specified. [config|c?]= # --config=file or --config (sets to "") **Syntax:** - `--config=value`: variable set to `value` - `--config`: variable set to empty string `""` - `-c`: sets to empty string; `-cvalue` form is **not** supported ## ARRAY (`@`) Collects multiple values into an array. Multiple specifications accumulate. A single option can contain delimited values (default: space, tab, comma; see [DELIM](#configuration)). Access with `"${include[@]}"`. To clear the array before adding values, use `getoptlong callback --before`. [include|I@]= # --include a --include b or --include a,b ## HASH (`%`) Collects `key=value` pairs into an associative array. Key without value is treated as `key=1`. Multiple pairs can be specified: `--define A=1,B=2` (see [DELIM](#configuration)). Access with `${define[KEY]}`, keys with `${!define[@]}`. To clear the hash before adding values, use `getoptlong callback --before`. [define|D%]= # --define KEY=VAL or --define KEY (KEY=1) ## CALLBACK (`!`) Calls a function when the option is parsed. Default function name is the option name with hyphens converted to underscores; use `getoptlong callback` to specify a custom function. Can combine with any type (`+!`, `:!`, `?!`, `@!`, `%!`). See ["CALLBACKS"](#callbacks) for registration and timing details. [action|a!]= # Calls action() when specified [file|f:!]= # Calls file() with argument # VALIDATION Option values can be validated using type specifiers or regex patterns: `=i` for integers, `=f` for floats, `=(` ... `)` for regex. [count:=i]=1 # Integer (positive/negative) [ratio:=f]=0.5 # Float (e.g., 123.45) [mode:=(^(a|b|c)$)]=a # Regex: exactly a, b, or c **Note:** For regex, the pattern extends to the last `)` in the definition, including any `)` in the description. Avoid using `)` in comments when using regex validation. Validation occurs before the value is stored or callbacks are invoked. For array options, each element is validated; for hash options, each `key=value` pair is matched as a whole. Error on validation failure (see [EXIT\_ON\_ERROR](#configuration)). # DESTINATION VARIABLE By default, values are stored in variables named after the option. A custom destination can be specified by adding the variable name after TYPE/MODIFIER and before VALIDATE: `[NAME|ALIAS:!DEST=(REGEX)]`. `PREFIX` setting applies to custom names too (see ["getoptlong init"](#getoptlong-init)). [count|c:COUNT]=1 # Store in $COUNT instead of $count [debug|d+DBG]=0 # Store in $DBG # HELP MESSAGE By default, `--help` and `-h` options are automatically available. They display a help message generated from option definitions and exit. No configuration is required. To customize or disable, use one of these methods (in order of precedence): [&HELP]="usage|u#Show usage" # 1. &HELP key in OPTS getoptlong init OPTS HELP="manual|m" # 2. HELP parameter in init [help|h # Custom help text]= # 3. Explicit option definition getoptlong init OPTS HELP="" # Disable help option ## SYNOPSIS (USAGE) Set the usage line displayed at the top of help output: [&USAGE]="Usage: cmd [options] " # In OPTS array getoptlong init OPTS USAGE="..." # Or via init parameter ## OPTION DESCRIPTIONS Text after `#` in the option definition becomes the help description. If omitted, a description is auto-generated. Default values are shown as `(default: value)`. [output|o: # Output file path]=/dev/stdout # CALLBACKS Callback functions are called when an option is parsed. The value is stored in the variable as usual, and the callback is invoked for additional processing such as validation or side effects. Callbacks work the same way with pass-through options. ## REGISTRATION Register callbacks with `getoptlong callback`. If function name is omitted or `-`, uses option name (hyphens to underscores). getoptlong callback