Last active
December 9, 2016 10:56
-
-
Save subk/03f94274fc1a015ca64bed1eba89d01a to your computer and use it in GitHub Desktop.
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 | |
# | |
# Export variables based on getopt long options | |
# Example usage: sample.sh | |
# | |
# parse options | |
LONG_OPTIONS=$(IFS=, echo "${ARGV_EXPORT_OPTIONS[@]}") | |
GETOPT="getopt" | |
[[ ! -z $ARGV_QUIET ]] && GETOPT="$GETOPT -q" | |
ARGV=$($GETOPT -o "" -l "$LONG_OPTIONS" -n 'options' -- "$@") | |
eval set -- "$ARGV" | |
# declare argv options as variable under prefix | |
while true; do | |
case "$1" in | |
-- ) | |
shift | |
break | |
;; | |
--* ) | |
# current option name without -- | |
CURRENT=${1:2} | |
# proper variable name | |
VARNAME=${CURRENT^^} # uppercase | |
VARNAME=${VARNAME//-/_} # - to _ | |
VARNAME=${ARGV_EXPORT_PREFIX}${VARNAME} | |
# check if option is a key=value or boolean | |
case "${ARGV_EXPORT_OPTIONS[@]}" in | |
# key=value | |
*"${CURRENT}:"* ) | |
if [ ! -z "$VARNAME" ]; then | |
REF="${VARNAME}[@]" | |
declare -a "$VARNAME"='(${!REF} $2)' | |
else | |
export ${VARNAME}=$2 | |
fi | |
shift | |
;; | |
# boolean | |
*"${CURRENT}"* ) | |
export ${VARNAME}=1 | |
;; | |
esac | |
;; | |
* ) | |
break | |
esac | |
shift | |
done |
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 | |
# ./sample.sh --username foo --password bar --option-flag --list abc --list def --list geh | |
MY_OPTIONS=( | |
"username:" | |
"password:" | |
"option-flag" | |
"list:" | |
) | |
ARGV_EXPORT_OPTIONS=${MY_OPTIONS[@]} \ | |
ARGV_EXPORT_PREFIX="MY_" \ | |
. argv-export.sh $@ | |
echo "username: $MY_USERNAME" | |
echo "password: $MY_PASSWORD" | |
echo "option-flag: $MY_OPTION_FLAG" | |
for i in ${MY_LIST[@]}; do | |
echo "item: $i" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment