shell学习笔记(数组)

bash只提供一维数组,并且没有限定数组的大小。类似与C语言,数组元素的下标由0开始编号。获取数组中的元素要利用下标。下标可以是整数或算术表达式,其值应大于或等于0。用户可以使用赋值语句对数组变量赋值。

     BASH中的数组有点怪,所以不常用到他们。然后如果需要用它们依然可以用,下标*和@指整个数组,${#array_name[*]}和${#array_name[@]}这两中特殊形式表示数组里元素的个数。不要把他们和似乎更合乎逻辑的${#array_name}搞混了,后者实际上是数组第一个元素的长度(等价于${#array_name[0]})。 其赋值有如下两种:

(1) name = (value1 ... valuen) 此时下标从0开始

(2) name[index] = value
1
2
3
4
[root@localhost ~]# echo ${#array[*]}    //使用${#array_name[*]}查看数组元素个数
2
[root@localhost ~]# echo ${#array[@]}    //使用${#array_name[@]}产看数组元素个数
2

数组操作(创建、删除、赋值):

1
2
3
4
5
6
7
8
9
[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 中数组管理的一些功能和缺陷:

1
2
3
4
5
6
7
8
9
10
11
[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

脚本输入如下:

1
2
3
4
5
6
7
8
[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

这个列子师傅很直观易懂,但只是因为我们已经把这个脚本构造得循规蹈矩了,人们一步小心就会犯错误,如果,用下面一句话替换for语句那行代码:

for elt in ${example[@]}; do
1
2
3
4
5
6
7
8
9
10
#!/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,效果如下:

1
2
3
4
5
6
7
8
9
[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

本文转自1594cqb 51CTO博客,原文链接:http://blog.51cto.com/wolfchen/1206111,如需转载请自行联系原作者
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值