Last active
August 31, 2017 19:55
-
-
Save gabesullice/e850eeb3a4640db0046dc7cf5ed6de71 to your computer and use it in GitHub Desktop.
Simple Shell Flag Parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
./flags.sh --your "a lunatic" --here
prints: