Skip to content

Instantly share code, notes, and snippets.

@SaurabhG20
Forked from jondkelley/readme.md
Created June 30, 2021 17:42
Show Gist options
  • Select an option

  • Save SaurabhG20/c3d482f3f077993359a3b98075bfcc24 to your computer and use it in GitHub Desktop.

Select an option

Save SaurabhG20/c3d482f3f077993359a3b98075bfcc24 to your computer and use it in GitHub Desktop.

Revisions

  1. Jonathan D Kelley revised this gist Dec 13, 2019. 1 changed file with 0 additions and 2 deletions.
    2 changes: 0 additions & 2 deletions readme.md
    Original file line number Diff line number Diff line change
    @@ -6,8 +6,6 @@
    TEST_MODE=FALSE
    ENDPOINT_HOSTNAME=""
    AUX=""
    # getopt args
    options=$(getopt -o THPSA: --long test,host,check_prefix,check_suffix,handlers: --name "$0" -- "$@")

    FLAG_LIST=(
    "test"
  2. Jonathan D Kelley created this gist Dec 13, 2019.
    66 changes: 66 additions & 0 deletions readme.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,66 @@
    # Bash getopt long options with values usage example

    ```sh
    #!/bin/bash -e
    # default args
    TEST_MODE=FALSE
    ENDPOINT_HOSTNAME=""
    AUX=""
    # getopt args
    options=$(getopt -o THPSA: --long test,host,check_prefix,check_suffix,handlers: --name "$0" -- "$@")

    FLAG_LIST=(
    "test"
    )

    ARGUMENT_LIST=(
    "endpoint"
    "argaux"
    )

    # read arguments
    opts=$(getopt \
    --longoptions "$(printf "%s," "${FLAG_LIST[@]}"),$(printf "%s:," "${ARGUMENT_LIST[@]}")" \
    --name "$(basename "$0")" \
    --options "" \
    -- "$@"
    )

    eval set --$opts

    while [[ $# -gt 0 ]]; do
    case "$1" in
    --test)
    TEST_MODE=TRUE
    shift;
    ;;
    --endpoint)
    ENDPOINT_HOSTNAME=$2
    shift 2
    ;;
    --argaux)
    AUX=$2
    shift 2
    ;;
    esac
    done

    echo TEST_MODE=$TEST_MODE
    echo ENDPOINT_HOSTNAME=$ENDPOINT_HOSTNAME
    echo AUX=$AUX
    # getopt args END
    ```



    **Note:** The `eval` in `eval set --$opts` is required as arguments returned by `getopt` are quoted.

    ## Example

    ```sh
    $ ./getopt.sh --test --endpoint "apple.com" --argaux "xyz"
    ```

    ## Reference
    - http://www.bahmanm.com/blogs/command-line-options-how-to-parse-in-bash-using-getopt
    - https://dustymabe.com/2013/05/17/easy-getopt-for-a-bash-script/