Tôi thích câu trả lời Robert McMahan của tốt nhất ở đây là có vẻ như đơn giản nhất để làm thành thể chia sẻ bao gồm file cho bất kỳ kịch bản của bạn để sử dụng. Nhưng có vẻ như có một lỗ hổng với dòng if [[ -n ${variables[$argument_label]} ]]
ném thông báo, "biến: chỉ số mảng xấu". Tôi không có đại diện để bình luận, và tôi nghi ngờ đây là 'sửa chữa' đúng đắn, nhưng gói rằng if
trong if [[ -n $argument_label ]] ; then
làm sạch nó.
Đây là mã tôi đã kết thúc, nếu bạn biết cách tốt hơn, hãy thêm nhận xét vào câu trả lời của Robert.
Bao gồm File "flags-declares.sh"
# declaring a couple of associative arrays
declare -A arguments=();
declare -A variables=();
# declaring an index integer
declare -i index=1;
Bao gồm File "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;
"script.sh" của bạn
. 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";
Nó có thể là một ý tưởng tốt để hỏi/kiểm tra tại http://unix.stackexchange.com/ cũng như – MRR0GERS
google cho "bash getopts" - rất nhiều hướng dẫn. –
@ glenn-jackman: Tôi chắc chắn sẽ google ngay bây giờ khi tôi biết tên. Điều về google là - để đặt câu hỏi - bạn đã biết 50% câu trả lời. – Stann