平时定义a=1;b=2;c=3,变量多了,再一个一个定义就费劲了。
简单的说数组就是数据类型的元素按一定顺序排列的集合。
数组就是有限个元素变量或数据用一个名字命名,然后用编号区分他们的变量的集合,这个名字称为数组,编号称为数组的下标。组成数组的多个变量称为数组的分量,也称为数组的元素,有时也称为下标变量。
(1) 数组的定义
一对括号表示数组,数组元素用“空格”符号分隔开
array=(value1 value2 value3….)
[root@shellbiancheng ~]# array=(1 2 3)
(2) 获取数组的长度
[root@shellbiancheng ~]# echo ${#array[*]}
3
[root@shellbiancheng ~]# echo ${#array[@]}
3
(3) 打印数组元素
[root@shellbiancheng ~]# echo ${array[0]}
1
[root@shellbiancheng ~]# echo ${array[1]}
2
[root@shellbiancheng ~]# echo ${array[2]}
3
[root@shellbiancheng ~]# echo ${array[*]}
1 2 3
(4) for循环打印数组
方法一:
[root@shellbiancheng jiaobenlianxi]# cat array01.sh
array=(
192.168.1.111
192.168.1.112
192.168.1.113
)
for ip in ${array[*]}
do
echo $ip
sleep 2
done
[root@shellbiancheng jiaobenlianxi]# sh array01.sh
192.168.1.111
192.168.1.112
192.168.1.113
方法二:用C语言方式
[root@shellbiancheng jiaobenlianxi]# cat array02.sh
array=(
192.168.1.114
192.168.1.115
192.168.1.116
)
for((i=0;i<${#array[*]};i++))
do
echo ${array[i]}
sleep 2
done
[root@shellbiancheng jiaobenlianxi]# sh array02.sh
192.168.1.114
192.168.1.115
192.168.1.116
(5) 数组的增加
[root@shellbiancheng jiaobenlianxi]# array=(1 2 3)
[root@shellbiancheng jiaobenlianxi]# echo ${array[*]}
1 2 3
[root@shellbiancheng jiaobenlianxi]# array[3]=4
[root@shellbiancheng jiaobenlianxi]# echo ${array[*]}
1 2 3 4
(6) 删除数组
[root@shellbiancheng jiaobenlianxi]# unset array[0]
[root@shellbiancheng jiaobenlianxi]# echo ${array[*]}
2 3 4
(7) 数组内容的截取和替换(和变量子串的替换很像)
截取:
[root@shellbiancheng jiaobenlianxi]# array=(1 2 3 4 5)
[root@shellbiancheng jiaobenlianxi]# echo ${array[*]:1:3}
2 3 4
[root@shellbiancheng jiaobenlianxi]# echo ${array[*]:3:4}
4 5
替换:
[root@shellbiancheng jiaobenlianxi]# echo ${array[*]/3/4} 把数组中的3替换成4临时替换,原数组未做改变
1 2 4 4 5
[root@shellbiancheng jiaobenlianxi]# array1=(${array[*]/3/4})
[root@shellbiancheng jiaobenlianxi]# echo ${array1[*]}
1 2 4 4 5
[root@shellbiancheng jiaobenlianxi]# array=($(ls))
[root@shellbiancheng jiaobenlianxi]# echo ${array[1]}
1.sh
[root@shellbiancheng jiaobenlianxi]# echo ${array[2]}
a.log
[root@shellbiancheng jiaobenlianxi]# echo ${array[3]}
array01.sh
[root@shellbiancheng jiaobenlianxi]# echo ${array[*]}
1-100.sh 1.sh a.log array01.sh array02.sh beijingcolor.sh b.log break.sh case01.sh check.sh chkconfigoff.sh chkconfigon.sh color1.sh color.sh for1-1000.sh for1-100_3.sh for1-100.sh for1.sh for2.sh for3.sh for4.sh for5.sh hanshu01.sh hanshu02.sh huafei.sh menufruit.sh nginx.sh piliangxiugai1.sh piliangxiugai2.sh piliangxiugai3.sh suijiwnjian.sh sum1-100.sh test uptime.sh usage.sh user.sh while1.sh while2.sh while3.sh while4.sh while.sh zhuajiu.sh
[root@shellbiancheng jiaobenlianxi]# cat array03.sh
array=(
$(ls)
)
for((i=0;i<${#array[*]};i++))
do
echo ${array[i]}
done
(1)定义:
静态数组:array=(1 2 3) 空格隔开
动态数组:array=($(ls))
给数组赋值:array[3]=4
(2)打印
打印所有元素:${array[*]}或${array[@]}
打印数组长度:${#array[@]}或${#array[*]}
打印单个元素:${array[i]} i是数组下标
原文地址:http://blog.51cto.com/10642812/2103603