Bash的奇怪输出(关联数组)

时间:2015-01-20 15:35:56

标签: bash associative-array bash4

我有这个数组:

declare -A modeAndAction
modeAndAction[category]=create
modeAndAction[attribute]=create
modeAndAction[customers]=create
modeAndAction[newsletter]=create
modeAndAction[vouchers]=create
modeAndAction[products]=create
modeAndAction[orders]=create

哪个输出:

Starting import of mode : attribute
With action: create
Starting import of mode : category
With action: create
Starting import of mode : newsletter
With action: create
Starting import of mode : vouchers
With action: create
Starting import of mode : orders
With action: create
Starting import of mode : customers
With action: create
Starting import of mode : products
With action: create

但我希望这个输出:

Starting import of mode : category
With action: create
Starting import of mode : attribute
With action: create
Starting import of mode : customer
With action: create
Starting import of mode : newsletter
With action: create
Starting import of mode : vouchers
With action: create
Starting import of mode : products
With action: create
Starting import of mode : orders
With action: create

所以一切都在输出中移动,忽略了它的声明,但我不明白为什么。 我希望模式(+它的动作)完全按照我声明的数组的顺序调用。

Bash版本:

GNU bash, version 4.2.51(1)-release (x86_64-pc-linux-gnu)

//编辑 我发现如果我有这个数组

modeAndAction[AAAAAAAAA]=create;
modeAndAction[B]=create;
modeAndAction[C]=create;
modeAndAction[D]=create;

我得到了这个输出:

Starting import of mode : B
With action: create
Starting import of mode : C
With action: create
Starting import of mode : D
With action: create
Starting import of mode : AAAAAAAAA
With action: create

所以它按关键长度自动排序。

// EDIT2 负责输出的代码

for i in "${!modeAndAction[@]}"
    do
        echo "Starting import of mode : $i"
        echo "With action: ${modeAndAction[$i]}"
    done

1 个答案:

答案 0 :(得分:1)

现在使用非关联数组键解决它:

    modeAndAction[0]=category
    modeAndAction[1]=attribute
    modeAndAction[2]=customers
    modeAndAction[3]=newsletter
    modeAndAction[4]=vouchers
    modeAndAction[5]=products
    modeAndAction[6]=orders


    for i in "${!modeAndAction[@]}"
    do
        echo "Starting import of mode : ${modeAndAction[$i]} with action create"
        # ...
    done