数组变量(Bash)

数组变量(Bash)

Content #

要为某个环境变量设置多个值,可以把值放在圆括号中,值与值之间以空格分隔:

$ mytest=(zero one two three four)

没什么特别的地方。如果想像普通环境变量那样显示数组,你会失望的:

$ echo $mytest
zero

以上代码只显示了数组的第一个值。要引用单个数组元素,必须使用表示其在数组中位置的索引。索引要写在方括号中,$符号之后的所有内容都要放入花括号中。

$ echo ${mytest[2]}
two

要显示整个数组变量,可以用通配符*作为索引:

$ echo ${mytest[*]}
zero one two three four

也可以改变某个索引位置上的值:

$ mytest[2]=seven
$ echo ${mytest[2]}
seven

甚至能用unset命令来删除数组中的某个值,但是要小心,这有点儿复杂。看下面的例子:

$ unset mytest[2]
$ echo ${mytest[*]}
zero one three four
$ echo ${mytest[2]}

$ echo ${mytest[3]}
three

这个例子用unset命令来删除索引2位置上的值。显示整个数组时,看起来好像其他索引已经填补了这个位置。但如果专门显示索引2位置上的值时,你会发现这个位置是空的。

可以在unset命令后跟上数组名来删除整个数组:

$ unset mytest
$ echo ${mytest[*]}

From #

Linux命令行与shell脚本编程大全