[root@localhost ~]# echo ${#array[*]} //使用${#array_name[*]}查看数组元素个数 2 [root@localhost ~]# echo ${#array[@]} //使用${#array_name[@]}产看数组元素个数 2
数组操作(创建、删除、赋值):
[root@localhost ~]# array=() //定义一个空数组 [root@localhost ~]# array=(one tow three 'Hello World') //创建一个有4个元素的数组 [root@localhost ~]# array[0]=hello //给数组赋值, [root@localhost ~]# array[1]=world [root@localhost ~]# echo ${array[1]} //访问数组单个元素 world [root@localhost ~]# unset array[1] //删除数组中第一个元素 [root@localhost ~]# unset array //删除整个数组
下面是一个快速脚本,它演示了bash 中数组管理的一些功能和缺陷:
[root@localhost shell]# cat array.sh #!/bin/bash example=(one tow three 'Hello World') example[4]=four echo "example[@] = ${example[@]}" echo "example array contains ${#example[@]} elements" for elt in "${example[@]}"; do echo "Element = $elt" done
脚本输入如下:
[root@localhost shell]# ./array.sh example[@] = one tow three Hello World four example array contains 5 elements Element = one Element = tow Element = three Element = Hello World Element = four
#!/bin/bash example=(one tow three 'Hello World') example[4]=four echo "example[@] = ${example[@]}" echo "example array contains ${#example[@]} elements" for elt in ${example[@]}; do echo "Element = $elt" done
(在数组表达式外面没有引号引起来)也能行,但它却不是输出4个元素而是5个:one、tow、three、Hello、World、four,效果如下:
[root@localhost shell]# ./arrs.sh example[@] = one tow three Hello World four example array contains 5 elements Element = one Element = tow Element = three Element = Hello Element = World Element = four
更多博客请访问 linux开源技术博客 http://www.chlinux.net/ 或者 平凡的日子 http://wolfchen.blog.51cto.com/