Skip to content

Instantly share code, notes, and snippets.

@deep-programmer
Forked from magnetikonline/README.md
Created September 9, 2018 16:34
Show Gist options
  • Select an option

  • Save deep-programmer/b3e1d417f335c8a5df748f9634ada723 to your computer and use it in GitHub Desktop.

Select an option

Save deep-programmer/b3e1d417f335c8a5df748f9634ada723 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

ARGUMENT_LIST=(
    "arg-one"
    "arg-two"
    "arg-three"
)


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

eval set --$opts

while [[ $# -gt 0 ]]; do
    case "$1" in
        --arg-one)
            argOne=$2
            shift 2
            ;;

        --arg-two)
            argTwo=$2
            shift 2
            ;;

        --arg-three)
            argThree=$2
            shift 2
            ;;

        *)
            break
            ;;
    esac
done

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

Example

$ ./getopt.sh --arg-one "apple" --arg-two "orange" --arg-three "banana"

Reference

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