声明一个数组但不定义它?

Com*_*erd 15 bash

有很多的导游 在那里展示了如何声明和定义数组

foo[0]=abc 
foo[1]=def
Run Code Online (Sandbox Code Playgroud)

我想要实现的是声明一个数组但不定义它,因为它不必立即定义,在大多数编程语言中它看起来像这样

int bar[100];
Run Code Online (Sandbox Code Playgroud)

这在shell脚本语言中可能吗?

kir*_*iri 24

您可以通过创建一个空数组来指定一个变量是一个数组,如下所示:

var_name=()
Run Code Online (Sandbox Code Playgroud)

var_name 然后将是一个数组,如报告

$ declare -p var_name
declare -a var_name='()'
Run Code Online (Sandbox Code Playgroud)

例子:

var_name=()
for i in {1..10}; do
    var_name[$i]="Field $i of the list"
done
declare -p var_name
echo "Field 5 is: ${var_name[5]}"
Run Code Online (Sandbox Code Playgroud)

它输出这样的东西:

declare -a var_name='([1]="Field 1 of the list" [2]="Field 2 of the list" [3]="Field 3 of the list" [4]="Field 4 of the list" [5]="Field 5 of the list" [6]="Field 6 of the list" [7]="Field 7 of the list" [8]="Field 8 of the list" [9]="Field 9 of the list" [10]="Field 10 of the list")'
Field 5 is: Field 5 of the list
Run Code Online (Sandbox Code Playgroud)