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.
Bash getopt long options with values usage example.

Bash getopt long options with values usage example

#!/bin/bash -e
# default args
TEST_MODE=FALSE
ENDPOINT_HOSTNAME=""
AUX=""

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

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

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment