Linux
帶有鍵值對的for循環,鍵是不維護排序順序
我有下面的腳本,我注意到在這種情況下,for循環的執行順序不是我指定的,即。預計為 2018、2019、2020,但結果為 2019、2018、2020。
在 shell 腳本中是否有特定的原因,有什麼方法可以保留順序。
#!/bin/sh declare -A arr arr=( ["2018"]=5%12 ["2019"]=1%12 ["2020"]=1%2 ) INPUT_MONTH=$2 INPUT_YEAR=$1 #For loop to iterate the year(key) value of array for year in ${!arr[@]}; do echo ${year} ${arr[${year}]} MONTH_RANGE=${arr[${year}]} if [ ${year} -ge ${INPUT_YEAR} ]; then START_MONTH=$(echo "${MONTH_RANGE}" | cut -d'%' -f 1) END_MONTH=$(echo "${MONTH_RANGE}" | cut -d'%' -f 2) # input year is equal and input month is different from default start one. if [ "${year}" == "${INPUT_YEAR}" ]; then START_MONTH=$INPUT_MONTH fi for mon in $(seq $START_MONTH $END_MONTH); do echo "Process year:month <=> ${year}:${mon}" done; else continue; fi done;
輸出:
2019 1%12 Process year:month <=> 2019:1 Process year:month <=> 2019:2 Process year:month <=> 2019:3 Process year:month <=> 2019:4 Process year:month <=> 2019:5 Process year:month <=> 2019:6 Process year:month <=> 2019:7 Process year:month <=> 2019:8 Process year:month <=> 2019:9 Process year:month <=> 2019:10 Process year:month <=> 2019:11 Process year:month <=> 2019:12 2018 5%12 Process year:month <=> 2018:4 Process year:month <=> 2018:5 Process year:month <=> 2018:6 Process year:month <=> 2018:7 Process year:month <=> 2018:8 Process year:month <=> 2018:9 Process year:month <=> 2018:10 Process year:month <=> 2018:11 Process year:month <=> 2018:12 2020 1%2 Process year:month <=> 2020:1 Process year:month <=> 2020:2
在 bash 中,
declare -A arr
聲明一個關聯數組。關聯數組中的鍵是散列的,並且${!arr[@]}
不能保證1的遍歷順序。$ declare -A arr $ arr=( ["2018"]=5%12 ["2019"]=1%12 ["2020"]=1%2 ) $ for year in "${!arr[@]}"; do printf '%s: %s\n' "${year}" "${arr[${year}]}"; done 2019: 1%12 2018: 5%12 2020: 1%2
相反,
declare -a arr
聲明一個索引數組,它應該按您的預期排序:$ declare -a arr $ arr=( [2018]=5%12 [2019]=1%12 [2020]=1%2 ) $ for year in "${!arr[@]}"; do printf '%s: %s\n' "${year}" "${arr[${year}]}"; done 2018: 5%12 2019: 1%12 2020: 1%2
由於您的鍵(年)是數字,因此在這種情況下似乎沒有理由不使用索引數組。
參考: