Getopt-Long-Bash

 view release on metacpan or  search on metacpan

GETOPTLONG.md  view on Meta::CPAN

    echo "Configuration file specified, but path is missing."
else
    echo "Using default configuration."
fi

if (( ${#library[@]} > 0 )); then
    echo "Library paths:"
    for libpath in "${library[@]}"; do
        echo "  - $libpath"
    done
fi

if (( ${#define[@]} > 0 )); then
    echo "Defined variables:"
    for key in "${!define[@]}"; do
        echo "  - $key = ${define[$key]}"
    done
fi

# Non-option arguments are available as positional parameters ($1, $2, etc.)
# after `eval "$(getoptlong set)"`.
# If PERMUTE=<array_name> was used during `getoptlong init` (or via &PERMUTE in OPTS),
# those non-option arguments are also available in the specified array.
if (( $# > 0 )); then
    echo "Remaining arguments ($#):"
    for arg in "$@"; do # Loop through positional parameters
        echo "  - $arg"
    done
fi
```

## 4. Detailed Option Definition

Command-line options for `getoptlong.sh` are defined using a Bash associative array. This section explains the detailed definition method and available option types.

### 4.1. Basic Syntax

Options are defined as keys in an associative array. The key string takes the following format:

`name[|aliases...][<type>[<modifier>]][destination][=<validation>] # description`

The value corresponding to this key in the associative array specifies the initial value of the option. Anything after a `#` in the key string is treated as a comment and used as the description in the auto-generated help message.

Example:

```bash
declare -A OPTS=(
    # NAME         ALIAS
    # |            | TYPE [:?@%]
    # |            | |MODIFIER [!>]
    # |            | ||VALIDATION
    # |            | |||      DESCRIPTION                    INITIAL VALUE
    # |            | |||      |                              |
    [ verbose    | v          # Output verbose information  ]=
    [ sweep      | w | ~W     # Enable sweep (-W disables)  ]=1
    [ output     | o :        # Specify output file         ]=/dev/stdout
    [ mode       | m ?        # Operation mode (optional)   ]=
    [ include    | i @        # Include path (multiple ok)  ]=()
    [ define     | D %        # Definition (KEY=VALUE)      ]=()
    [ execute    | x  !       # Execute command             ]=my_execute_function
    [ count      | N : =i     # Number of iterations (int)  ]=1
    [ ratio      | r : =f     # Ratio (float)               ]=0.5
    [ id         | K : =(^[a-z0-9_]+$) # ID (alphanum & _)  ]=default_id
)
```

*   **`name`:** (Required) The long option name following `--` (e.g., `verbose`).  Can contain hyphens (e.g., `very-verbose`). This is also the default base for the variable name where the option's value is stored (hyphens replaced by underscores), u...

*   **`aliases`:** (Optional) One or more option aliases, each following a `-` (e.g., `v`).  Multiple aliases can be specified, separated by `|` (e.g., `long|s|t`).  If only a short name is defined (e.g., `[s:]`), it also serves as the base for the v...

*   **`type` (Type Specifier):** (Optional) A single character that specifies how the option handles arguments. If omitted, it defaults to `+` (flag/counter type).  Possible values are:
    *   `+`: Flag option. See section 3.2.1 for behavior.
    *   `:`: Option requires an argument.
    *   `?`: Option takes an optional argument.
    *   `@`: Option can be specified multiple times; values are stored in an array.
    *   `%`: Option takes `key=value` pairs, stored in an associative array.

*   **`modifier`:** (Optional) Special characters that alter the option's behavior, immediately following the `type` (if any):

    *   `!`: Callback. The specified function (or a default one based on the option name or `destination`) is called when this option is parsed. See Section 3.3 if specifying a destination variable.

    *   `>`: Passthrough. The option and its argument (if any) are collected into a specified array. This must follow a `type`. See Section "5.3. Option Pass-through".

    These can be combined (e.g., `!>`).

*   **`destination`:** (Optional) Specifies a custom variable name where the option's value will be stored. This name appears directly after the `type_char` and any `modifiers`.  See Section "3.3. Specifying Destination Variable Name" for full detail...

*   **`=<validation>`:** (Optional) Specifies validation for the argument's value. This follows the `destination` if present, or the `type`/`modifier` otherwise.  See details in Section "4.4. Value Validation". Examples: `=i` (integer), `=f` (float),...

*   **`# description`:** Text following `#` is used as the option's description in the help message.

*   **INITIAL VALUE:** Specified as the value of the associative array element.  This becomes the default value if the option is not provided on the command line.  Behavior varies by type if not specified (e.g., flags default to empty string, arrays ...

After parsing with `getoptlong parse` and setting variables with `eval "$(getoptlong set)"`, shell variables corresponding to the options (either default names or custom `destination` names) are populated.  The `PREFIX` configuration can add a common...

### 4.2. Option Types and Type Specifiers

#### 4.2.1. Flag Options (No Suffix or `+`)

Act as switches that do not take arguments and can be used as both simple flags and counters. The `+` type specifier is the default if no other type specifier is provided.

*   **Definition Examples:**
    *   `[verbose|v  # Verbose output ]=` (Equivalent to `[verbose|v+]`)
    *   `[debug|d+   # Debug level    ]=0` (Initial value for easier variable reference)
    *   `[feature|f  # Enable feature ]=`
    *   `[sweep|w|~W # Enable sweep   ]=1` (with negative alias `-W`)
    *   `[verbose|v|~q|~quiet]=` (`-q`/`--quiet` negate, `--no-quiet` re-enables)

*   **How to Specify:** `-v`, `--verbose`, `--debug`, `-d`, `--feature`

*   **Variable Behavior:**
    *   First specification: Variable is set to `1`
    *   Multiple specifications (e.g., `-vvv` or `--debug --debug`): Variable value increments
    *   Specifying with `no-` prefix (e.g., `--no-debug`): Variable is reset to empty string
    *   Specifying with a negative alias (e.g., `-W` for `[sweep|w|~W]`, or `--quiet` for `[verbose|v|~q|~quiet]`): Variable is reset to empty string, equivalent to `--no-<name>`

*   **Use Cases:** Boolean flags, verbosity levels, debug levels. Setting an initial numeric value (e.g., `]=0`) makes variable reference simpler in arithmetic contexts like `(( debug > 0 ))`.

#### 4.2.2. Required Argument Options (`:`)

Options that always require a value.

GETOPTLONG.md  view on Meta::CPAN

#### 4.2.6. Callback Options (`!`)

When the option is parsed, the specified callback function is called. This `!` specifier can be appended to any of the above option types (`+`, `:`, `?`, `@`, `%`).

*   **Definition Examples:**
    *   `[execute|x! # Execute a command]` (flag type callback)
    *   `[config|c:! # Load a configuration file]` (required argument type callback)

*   **Behavior:**
    *   When the option is specified on the command line, the associated callback function is executed.
    *   By default, the callback function name is the same as the option's long name (hyphens converted to underscores). An arbitrary function name can be specified using the `getoptlong callback` command.
    *   For callback function invocation timing and arguments, see Section "7.4. `getoptlong callback ...`" and "5.1. Callback Function Details".

*   **Use Cases:** Executing custom actions during option parsing, complex value processing, immediate configuration changes.

### 4.3. Specifying Destination Variable Name

By default, `getoptlong.sh` stores the value of a parsed option (e.g., `--my-option value`) into a shell variable derived from the option's long name (e.g., `$my_option`, with hyphens replaced by underscores).  However, you can specify a custom varia...

This is achieved by writing the desired variable name directly after the option type specifier (e.g., `+`, `:`, `?`, `@`, `%`) and any modifiers (e.g., `!`, `-`).

*   **Syntax in Option Definition:** Refer back to Section "4.1. Basic Syntax" for the full structure: `long_name[|short_name...][<type_char>[<modifiers>]][DEST_VAR_NAME][=<validation_type>] # Description` The `DEST_VAR_NAME` is the custom variable n...

*   **Example from `ex/dest.sh`:**
    The script `ex/dest.sh` demonstrates this feature:
    ```bash
    declare -A OPTS=(
        [ count     | c :COUNT=i # repeat count              ]=1
        [ sleep     | i @SLEEP=f # interval time             ]=
        [ paragraph | p ?PARA    # print newline after cycle ]=
        [ trace     | x !TRACE   # trace execution           ]= # TRACE becomes var name for callback context
        [ debug     | d +DEBUG   # debug level               ]=0
        [ message   | m %MSG=(^(BEGIN|END|EACH)=) # print message at BEGIN|END|EACH ]=
    )
    ```
    In this example:
    *   `[count|c:COUNT=i]`: Stores the value of `--count` into `COUNT` (validated as integer).
    *   `[sleep|i@SLEEP=f]`: Stores values for `--sleep` into array `SLEEP` (validated as floats).
    *   `[paragraph|p?PARA]`: Stores optional arg of `--paragraph` into `PARA`.
    *   `[debug|d+DEBUG]`: Stores incrementing value of `--debug` into `DEBUG`.
    *   `[message|m%MSG=(...)]`: Stores key-value pairs from `--message` into associative array `MSG`.

*   **Behavior:**
    *   After `getoptlong parse "$@"` and `eval "$(getoptlong set)"`, the specified variables (`COUNT`, `SLEEP`, `PARA`, `DEBUG`, `MSG` in the example) will contain the parsed values.
    *   This per-option destination variable specification overrides the default variable naming convention based on `long_name` or `short_name`.
    *   The `PREFIX` configuration setting (see Section "7.1. `getoptlong init ...`") will also apply to these custom variable names. For example, if `PREFIX=MY_` and an option is `[opt:VAR]`, the value will be stored in `$MY_VAR`.

*   **Use Cases:**
    *   Using more descriptive or conventional variable names (e.g., `ALL_CAPS` for global settings).
    *   Avoiding naming conflicts with other variables or functions.
    *   Improving code readability by explicitly showing where an option's value is stored.

### 4.4. Value Validation

There is a feature to validate the values of arguments passed to options. Validation is specified by appending `=<validation_type>` to the end of the option definition.

#### 4.4.1. Integer Validation (`=i`)

Validates if the argument is an integer.

*   **Definition Example:** `[count|c:COUNT=i # Number of iterations]` (assuming COUNT is the destination variable) or `[count|c:=i # Number of iterations]` (if using default variable name).

*   **Behavior:** If the argument is not an integer, an error message is displayed, and the script exits (default behavior, if `EXIT_ON_ERROR=1`).

*   Applicable to array options (`@...=i`) and the value part of hash options (`%...=i`).

#### 4.4.2. Float Validation (`=f`)

Validates if the argument is a floating-point number.

*   **Definition Example:** `[ratio|r:RATIO=f # Ratio]` or `[ratio|r:=f # Ratio]`

*   **Behavior:** If the argument is not a floating-point number (e.g., `123.45` is OK, `1.2e-3` may not be supported), an error message is displayed, and the script exits.

*   Applicable to array options (`@...=f`) and the value part of hash options (`%...=f`).

#### 4.4.3. Custom Regex Validation (`=(<regex>)`)

Validates if the argument matches the specified Bash extended regular expression (ERE). The regex is from the `(` immediately following `=` to the corresponding final `)`.

*   **Definition Examples:**
    *   `[mode|m:=(^(fast|slow|debug)$)]` (one of fast, slow, debug)
    *   `[name|N@=(^[A-Za-z_]+$)]` (each element contains only letters and underscores)
    *   `[param|P%:=(^[a-z_]+=[0-9]+$)]` (key is lowercase letters and _, value is numbers)

*   **Behavior:** If the argument does not match the regex, an error message is displayed, and the script exits.

*   Applicable to array and hash options. For arrays, each element is validated. For hashes, each `key=value` pair as a whole is validated against the regex.

## 5. Help Message Generation and Customization

`getoptlong.sh` provides a powerful feature to automatically generate help messages that show users how to use the script. This significantly reduces the developer's effort in manually managing help text. The generated help message displays options i...

### 5.1. Automatic Help Option

`getoptlong.sh` automatically provides a help option (or options) that, when invoked,
displays a generated help message and exits the script.

*   **Default Behavior:**

    *   By default, `--help` and `-h` are recognized as help options.
    *   If not defined in your `OPTS` array, `getoptlong.sh` implicitly adds `help|h#show help`.
    *   When parsed, the help message is shown, and the script exits with status 0.

*   **Customization:** You can change the name, alias, and description of this automatic help option using:

    1.  **`&HELP` key in `OPTS` array (Highest Precedence):**

        ```bash
        declare -A OPTS=(
            [&HELP]="show-usage|u#Displays usage information and exits."
            # ... other option definitions ...
        )
        getoptlong init OPTS
        ```

        Now, `--show-usage` or `-u` will trigger the help message.

    2.  **`HELP` parameter in `getoptlong init` (Lower Precedence):**

        ```bash



( run in 0.519 second using v1.01-cache-2.11-cpan-71847e10f99 )