我有這些變數:
bridge_xa_name_list=( "$br_int0_srxa" "$br_int1_srxa" "$br_int2_srxa" "$br_int6_srxa" "$br_int7_srxa" "$br_wan3_srxa1" "$br_wan3_srxa2" )
bridge_xb_name_list=( "$br_int0_srxb" "$br_int1_srxb" "$br_int2_srxb" "$br_int6_srxb" "$br_int7_srxb" "$br_wan3_srxb1" "$br_wan3_srxb2" )
我正在嘗試使用單個回圈來迭代每個陣列的所有元素。
目前我有一個正常運行的回圈,但只能通過參考 $bridge_xa_name_list
for a in "${bridge_xa_name_list[@]}"; do
shell_echo_textval_green "Network Bridge Name Detected" "$a"
sleep 1
shell_echo_text "Verifying $a network State"
virsh_net_list=$(virsh net-list | grep active | grep $a)
if [[ ! $virsh_net_list == *"active" ]]
then
shell_echo "[Inactive]"
else
shell_echo "[Active]"
shell_echo_green "$a.xml found. Undefining anyway."
virsh net-undefine $a
fi
shell_echo_text "File $a.xml is at $srxa_fld_path"
if [[ -f ${srxa_fld_path}${a}.xml ]]
then
shell_echo "[Yes]"
else
shell_echo "[Not Found]"
shell_echo_text "Attempting to copy $a.xml template to ~/config/$srxa_nm"
cp $xml_file_path $srxa_fld_path${a}.xml
shell_echo ["Copied"]
#Check if Copy was sucessfull
if [[ -f $srxa_fld_path${a}.xml ]]
then
:
else
shell_echo_red "[Failed]"
shell_echo_red "There was an error when trying to copy ${a}.xml"
shell_echo_error_banner "Script Aborted! 1 error(s)"
exit 1
fi
done
我腳本中的$a正在迭代第一個陣列中的所有元素。但是,我想將第二個陣列作為同一回圈的一部分。
uj5u.com熱心網友回復:
這些是索引陣列,因此您可以遍歷索引:
for (( i = 0; i < ${#bridge_xa_name_list[@]}; i )); do
echo "${bridge_xa_name_list[i]}"
echo "${bridge_xb_name_list[i]}"
done
uj5u.com熱心網友回復:
我腳本中的$a正在迭代第一個陣列中的所有元素。但是,我想將第二個陣列作為同一回圈的一部分。
我認為你的意思是你想為 的每個元素執行一次回圈體,bridge_xa_name_list并且為 的每個元素分別執行一次bridge_xb_name_list,而不復制回圈體。是的,至少有兩種簡單的方法可以做到這一點:
最簡單的方法是在回圈頭中指定附加元素:
for a in "${bridge_xa_name_list[@]}" "${bridge_xb_name_list[@]}"; do # loop body ...您需要在這里了解的是
for回圈語法與訪問陣列沒有特別的關系。這種命令的in串列指定了零個或多個單獨的值(shell“單詞”)進行迭代,在您的原始代碼的情況下,這些值是由涉及 array-valued parameter 的引數擴展產生的bridge_xa_name_list。但這只是shell在執行每個命令之前擴展每個命令(路徑擴展、引數擴展、命令擴展等)的一般程序的一個特例。你可以隨心所欲地使用它。或者
在回圈周圍創建一個函式,為每個函式引數執行一次。然后為每個陣列呼叫一次該函式:
my_loop() { for a in "$@"; do # loop body done } # ... my_loop "${bridge_xa_name_list[@]}" my_loop "${bridge_xb_name_list[@]}"請注意,這仍然表現出與前一項中描述的相同的擴展然后執行行為,這就是為什么您必須傳遞每個陣列的擴展(每個元素一個單詞)。沒有直接的方法將整個陣列作為單個引數傳遞。
另請注意,shell 支持一種特殊的快捷方式來遍歷
$@. 對于這種特殊情況,您可以in完全省略該串列:my_loop() { for a; do # loop body done }
當然,您也可以通過提供函式并使用兩個陣列的元素呼叫一次來組合上述內容:
my_loop "${bridge_xa_name_list[@]}" "${bridge_xb_name_list[@]}"
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/472113.html
上一篇:函式中的區域變數
