Skip to content

Instantly share code, notes, and snippets.

@v5tech
Forked from magnetikonline/README.md
Created January 29, 2023 04:58
Show Gist options
  • Save v5tech/da15ab53dcd3653dcaee9a97e205f5e3 to your computer and use it in GitHub Desktop.
Save v5tech/da15ab53dcd3653dcaee9a97e205f5e3 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