Skip to content

Instantly share code, notes, and snippets.

@strickc
Created September 11, 2018 20:21
Show Gist options
  • Save strickc/bffc6cb4e4e25e3e9e997697f5f07c66 to your computer and use it in GitHub Desktop.
Save strickc/bffc6cb4e4e25e3e9e997697f5f07c66 to your computer and use it in GitHub Desktop.
Bash options parser
# this script can be SOURCED by any other script to get options in local variables
# SCRIPTOPTx and OPTARGx (if x designated as `x:` to request an argument)
# i.e. from parent script:
# declare -A SCRIPTOPTS=( \
# [s]="Save to backup loaction" \
# [n:]="Copy resulting dtb to NFS boot folder, at designated location" \
# )
# `source ./0optParser.sh "$@"`
function printHelp {
echo $1
echo "Available options:"
for K in "${!SCRIPTOPTS[@]}"; do
echo " $(echo $K | sed 's/://g') - ${SCRIPTOPTS[$K]}"
done
exit -1
}
if [ ! ${SCRIPTOPTS[h]+_} ]; then SCRIPTOPTS[h]="Print help"; fi
# assign any opt .i.e. x defined above and provided in command line to variable i.e. SCRIPTOPTx
while getopts ":$(echo ${!SCRIPTOPTS[@]} | sed 's/ //g')" opt; do
if [ "$opt" == "?" ]; then
printHelp "Invalid option: -$OPTARG"
elif [ "$opt" == ":" ]; then
printHelp "Option -$OPTARG requires an argument."
else
if [ $OPTARG ]; then
eval "OPTARG${opt}=$OPTARG"
echo "Option ${opt} selected: ${SCRIPTOPTS[${opt}:]}"
else
echo "Option ${opt} selected: ${SCRIPTOPTS[$opt]}"
fi
eval "SCRIPTOPT${opt}=y"
fi
done
if [ $SCRIPTOPTh ]; then printHelp; fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment