声明数组但不定义它?


14

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

foo[0]=abc 
foo[1]=def

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

int bar[100];

Shell脚本语言可以做到这一点吗?

Answers:


23

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

var_name=()

var_name 然后将是由报告的数组

$ declare -p var_name
declare -a var_name='()'

例:

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]}"

输出如下所示:

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

minerz029,@am:..以及如何定义元素?我试过了,但是只能定义/访问单个字符串。.一个小例子来定义和访问数组变量的值会很棒...
2014年

很好地弄清楚了..我错过了括号..
精确的

4

除了上述方式,我们还可以通过声明语句创建一个数组。

带-a选项的define语句可用于将变量声明为数组,但这不是必需的。没有明确定义,所有变量都可以用作数组。实际上,从某种意义上来说,似乎所有变量都是数组,并且没有下标的赋值与分配给“ [0]”的含义相同。数组的显式声明是使用内置的声明完成的:

declare -a ARRAYNAME

关联数组是使用以下方法创建的

declare -A name.

可以使用clarify和readonly内置函数为数组变量指定属性。每个属性都适用于数组的所有成员。

设置任何数组变量后,可以按以下方式访问它:

${array_name[index]}

1

这实际上与C相同。在C中,我们可以根据需要选择array。在这里,我们可以取一个空数组,然后放置任何值。

bar=()

Simple For Loop可以在该数组中取值并打印:

bar=()
for ((i=0;i<10;i++));
do
    read bar[$i]  #Take Value in bar array
    echo bar[$i]
done

希望能帮助到你。


答案是什么问题?为什么要投下反对票?
Maniruzzaman Akash
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.