Skip to content

Instantly share code, notes, and snippets.

@simonmichael
Created July 8, 2023 17:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonmichael/c5a28602b136982c4b45704a01a16db7 to your computer and use it in GitHub Desktop.
Save simonmichael/c5a28602b136982c4b45704a01a16db7 to your computer and use it in GitHub Desktop.
options parsing in bash
declare -A FLAGS
declare -a ARGS
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
-h|--help)
FLAGS[--help]=1
shift
;;
-p|--pause)
FLAGS[--pause]=1
shift
;;
*)
if [[ "$1" = --no-* ]]
then
FLAGS[$1]=1
shift
elif [[ "$1" = --* ]]
then
FLAGS[$1]=1
STEPS=1
shift
elif [[ "$1" = -* ]]
then
echo "Error: unknown flag $1, use double-hypen for step flags"
exit 1
else
ARGS+=("$1")
shift
fi
;;
esac
done
if [[ ${FLAGS[--help]} = 1 ]]; then usage; exit; fi
hostname="${ARGS[0]:-foo}"
adminemail="${ARGS[1]:-bar}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment