Skip to content

Instantly share code, notes, and snippets.

@andrewwheal
Created November 11, 2015 17:04
Show Gist options
  • Save andrewwheal/147390e2be9d3c42d3a4 to your computer and use it in GitHub Desktop.
Save andrewwheal/147390e2be9d3c42d3a4 to your computer and use it in GitHub Desktop.
Bash Option Parsing
#!/bin/bash
# Include this file in the top of your script to have options
# parsed into an OPTIONS variable.
#
# If you set an OPTSTRING variable, getopts will be used with that string
#
# If you set an OPTION_DEBUG variable, then the parsed options will be output
declare -A OPTIONS
if [ -n "$OPTSTRING" ]; then
# OPTSTRING is set to use getopts
while getopts "$OPTSTRING" opt; do
[ -z "$OPTARG" ] && OPTARG=1
OPTIONS["$opt"]=$OPTARG
done
else
# OPTSTRING is not set so manually parse options
while true; do
case "$1" in
--) # option breaker
shift
break
;;
--*) # long option
OPTIONS[${1#-}]=1
shift
;;
-*) ## short option(s)
for (( i=1; i<${#1}; i++ )); do
opt="${1:$i:1}"
if [[ $i == $((${#1}-1)) && "$2" != -* && "$3" == -* ]]; then
# option has value
OPTIONS["$opt"]=$2
shift
shift
continue 2
else
# just a normal option
if [[ -z "${OPTIONS[$opt]}" || ! "${OPTIONS[$opt]}" =~ ^^[0-9]+$ ]]; then
# first instance so set to 1
OPTIONS["$opt"]=1
else
# recurring instance so increment
((OPTIONS["$opt"]++))
fi
fi
done
shift
;;
*) # non option
break
;;
esac
done
fi
if [ -n "$OPTION_DEBUG" ]; then
echo -e "\n----- OPTION DEBUG -----"
for i in "${!OPTIONS[@]}"; do
echo "$i = ${OPTIONS[$i]}"
done
echo "------ PARAMETERS ------"
for i in "${@}"; do
echo "$i"
done
echo -e "------------------------\n"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment