Skip to content

Instantly share code, notes, and snippets.

@gabesullice
Last active August 31, 2017 19:55
Show Gist options
  • Save gabesullice/e850eeb3a4640db0046dc7cf5ed6de71 to your computer and use it in GitHub Desktop.
Save gabesullice/e850eeb3a4640db0046dc7cf5ed6de71 to your computer and use it in GitHub Desktop.
Simple Shell Flag Parsing
#!/bin/bash
set -e
declare -A options
options["your"]=false
options["options"]=false
options["here"]=false
main () {
parse_options "$@"
for option in ${!options[@]}; do
echo $option ${options[$option]}
done
}
parse_options () {
local args=( "$@" )
for option in ${!options[@]}; do
for index in ${!args[@]}; do
local flag=${args[$index]}
if [ "$flag" = "--$option" ]; then
local next="${args[$index + 1]}"
if [[ $next == "" ]] || [[ $next =~ ^--.* ]]; then
options[$option]=true
else
options[$option]=$next
fi
fi
done
done
}
main "$@"
@gabesullice
Copy link
Author

./flags.sh --your "a lunatic" --here

prints:

your a lunatic
options false
here true

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