Skip to content

Instantly share code, notes, and snippets.

@four43
Created February 23, 2019 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save four43/b4a09ba757a5d893677f6d565e288692 to your computer and use it in GitHub Desktop.
Save four43/b4a09ba757a5d893677f6d565e288692 to your computer and use it in GitHub Desktop.
A better usage of Bash's getopt or getop which can handle = properly
#!/bin/bash
set -e
USAGE="$(basename "$0") -a [ARGUMENT A] --b [ARGUMENT_B] [-c [ARGUMENT_C]] -- Creates a docker tag from supplied info
where:
-a|--arga The first argument, A
-b|--argb The second argument, B
-c|--argc The third argument, C
"
ARGS=("$@")
# read the options
while [[ "${#ARGS[@]}" -gt 0 ]]; do
KEY="${ARGS[0]}"
VALUE="${ARGS[1]}"
case "${KEY}" in
-a|--arga)
ARG_A="$VALUE"
ARGS=("${ARGS[@]:2}")
;;
-b|--argb)
ARG_B="$VALUE"
ARGS=("${ARGS[@]:2}")
;;
-c|--argc)
ARG_C="$VALUE"
ARGS=("${ARGS[@]:2}")
;;
-h|--help)
echo "${USAGE}" >&2
exit 0
;;
*) # Unknown Option or "key=value"
while IFS='=' read -ra SPLIT <<< ${KEY}; do
# Split by the "=" and add back to our arguments array
for i in "${SPLIT[@]}"; do
ARGS+=("${i}")
done
FOUND_SPLIT=1
ARGS=("${ARGS[@]:1}")
break
done
if [[ -z "${FOUND_SPLIT}" ]]; then
echo "Unknown option $1"
echo "${USAGE}"
exit 1
fi
;;
--)
ARGS=("${ARGS[@]:1}")
break
;;
esac
done
echo "ARG_A: ${ARG_A}"
echo "ARG_B: ${ARG_B}"
echo "ARG_C: ${ARG_C}"
# Test cases:
# ./getopt_better_example.sh -a hello --argb "world --argc="it works"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment