[shell] for循环数组保持排序

for循环数组时,自动改变顺序按A-Z排序

[root@XM-v106 ~]# cat b.sh 
#!/bin/bash
declare -A array
array=([B]=1 [A]=2 [E]=7 [D]=4 [C]=3 )
for i in ${!array[*]}
do
    echo "$i -> ${array[$i]}"
done
[root@XM-v106 ~]# bash b.sh 
A -> 2
B -> 1
C -> 3
D -> 4
E -> 7

 保持排序

[root@XM-v106 ~]# cat a.sh
#!/bin/bash
declare -a array=(B A C)
declare -a A=(1 2 3)
declare -a B=(4 5 6)
declare -a C=(7 8 9)
for i in ${array[@]}
do
    field1=$(eval echo \${$i[0]})
    field2=$(eval echo \${$i[1]})
    field3=$(eval echo \${$i[2]})
    echo $i
    echo "    "field1:$field1
    echo "    "field2:$field2
    echo "    "field2:$field3
done
[root@XM-v106 ~]# bash a.sh
B
    field1:4
    field2:5
    field2:6
A
    field1:1
    field2:2
    field2:3
C
    field1:7
    field2:8
    field2:9

 

posted @ 2019-03-29 15:33  金枪语  阅读(747)  评论(0编辑  收藏  举报