Lubię odpowiedź Roberta McMahan jest najlepszy tutaj, gdyż wydaje się, że najłatwiej przekształcić udostępnianych zawierać pliki dowolnych skryptów posługiwać się. Ale wydaje się, że ma ona wadę w linii if [[ -n ${variables[$argument_label]} ]]
rzucającej komunikat "zmienne: niepoprawny indeks tablicy". Nie mam przedstawiciela, który mógłby skomentować, i wątpię, czy jest to poprawna "poprawka", ale owija ją: if
w if [[ -n $argument_label ]] ; then
czyści to.
Oto kod, który znalazłem, jeśli znasz lepszy sposób, proszę dodać komentarz do odpowiedzi Roberta.
Dołącz plik "flags-declares.sh"
# declaring a couple of associative arrays
declare -A arguments=();
declare -A variables=();
# declaring an index integer
declare -i index=1;
Dołącz plik "flags-arguments.sh"
# [email protected] here represents all arguments passed in
for i in "[email protected]"
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;
Twój "script.sh"
. 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";
Może być dobrym pomysłem zapytać/sprawdzić na http://unix.stackexchange.com/ oraz – MRR0GERS
google dla "bash getopts" - wiele samouczków. –
@ glenn-jackman: Na pewno google teraz, gdy znam nazwę. Rzecz w google to - zadać pytanie - powinieneś już znać 50% odpowiedzi. – Stann