是否可以在bash中为稀疏数组设置默认值?

时间:2013-12-18 08:34:35

标签: arrays bash

例如,如果我有这个数组:

SourceFolder[0]="inbound1"
SourceFolder[1]="inbound2"
SourceFolder[2]="inbound3"
SourceFolder[100]="inbound100"

我经历过:

for i in "${!SourceFolder[@]}"
do
 echo "SourceFolder: " ${SourceFolder[$i]}
done

是否可以让它为未初始化的索引(3-99)返回一些默认值?

因此,对于从3到99的索引,它将返回,例如,“defaultFolder”

1 个答案:

答案 0 :(得分:1)

#!/usr/bin/env bash

for i in {0..100}; do
    SourceFolder["${i}"]="defaultFolder"
done

SourceFolder[0]="inbound1"
SourceFolder[1]="inbound2"
SourceFolder[2]="inbound3"
SourceFolder[100]="inbound100"

for i in "${!SourceFolder[@]}"; do
    echo "SourceFolder: ${SourceFolder[$i]}"
done