Saya suka jawaban Robert McMahan yang terbaik di sini karena tampaknya yang termudah untuk dibuat menjadi file sharable menyertakan untuk skrip Anda untuk digunakan. Tetapi tampaknya memiliki cacat dengan garis if [[ -n ${variables[$argument_label]} ]]melemparkan pesan, "variabel: array array yang buruk". Saya tidak punya perwakilan untuk berkomentar, dan saya ragu ini adalah 'perbaikan' yang tepat, tetapi membungkusnya ifdengan if [[ -n $argument_label ]] ; thenmembersihkannya.
Inilah kode yang akhirnya saya dapatkan, jika Anda tahu cara yang lebih baik, silakan tambahkan komentar pada jawaban Robert.
Sertakan File "flags-declares.sh"
# declaring a couple of associative arrays
declare -A arguments=();
declare -A variables=();
# declaring an index integer
declare -i index=1;
Sertakan File "flags-arguments.sh"
# $@ here represents all arguments passed in
for i in "$@"
do
arguments[$index]=$i;
prev_index="$(expr $index - 1)";
# this if block does something akin to "where $i contains ="
# "%=*" here strips out everything from the = to the end of the argument leaving only the label
if [[ $i == *"="* ]]
then argument_label=${i%=*}
else argument_label=${arguments[$prev_index]}
fi
if [[ -n $argument_label ]] ; then
# this if block only evaluates to true if the argument label exists in the variables array
if [[ -n ${variables[$argument_label]} ]] ; then
# dynamically creating variables names using declare
# "#$argument_label=" here strips out the label leaving only the value
if [[ $i == *"="* ]]
then declare ${variables[$argument_label]}=${i#$argument_label=}
else declare ${variables[$argument_label]}=${arguments[$index]}
fi
fi
fi
index=index+1;
done;
"Script.sh" Anda
. bin/includes/flags-declares.sh
# any variables you want to use here
# on the left left side is argument label or key (entered at the command line along with it's value)
# on the right side is the variable name the value of these arguments should be mapped to.
# (the examples above show how these are being passed into this script)
variables["-gu"]="git_user";
variables["--git-user"]="git_user";
variables["-gb"]="git_branch";
variables["--git-branch"]="git_branch";
variables["-dbr"]="db_fqdn";
variables["--db-redirect"]="db_fqdn";
variables["-e"]="environment";
variables["--environment"]="environment";
. bin/includes/flags-arguments.sh
# then you could simply use the variables like so:
echo "$git_user";
echo "$git_branch";
echo "$db_fqdn";
echo "$environment";