Shell数组变量
2018-05-09 本文已影响0人
心疼你萌萌哒
Shell数组变量
========================================================
普通数组:只能使用整数作为数组索引
关联数组:可以使用字符串作为数组索引
一、普通数组
定义数组:
方法一: 一次赋一个值
数组名[下标]=变量值
# array1[0]=pear
# array1[1]=apple
# array1[2]=orange
# array1[3]=peach
方法二: 一次赋多个值
# array2=(tom jack alice)
# array3=(`cat /etc/passwd`) 希望是将该文件中的每一个行作为一个元数赋值给数组array3
# array4=(`ls /var/ftp/Shell/for*`)
# array5=(tom jack alice "bash shell")
# colors=($red $blue $green $recolor)
# array5=(1 2 3 4 5 6 7 "linux shell" [20]=puppet)
查看数组:
# declare -a
declare -a array1='([0]="pear" [1]="apple" [2]="orange" [3]="peach")'
declare -a array2='([0]="tom" [1]="jack" [2]="alice")'
访问数组元数:
# echo ${array1[0]} 访问数组中的第一个元数
# echo ${array1[@]} 访问数组中所有元数 等同于 echo ${array1[*]}
# echo ${#array1[@]} 统计数组元数的个数
# echo ${!array2[@]} 获取数组元数的索引
# echo ${array1[@]:1} 从数组下标1开始
# echo ${array1[@]:1:2} 从数组下标1开始,访问两个元素
遍历数组:
方法一: 通过数组元数的个数进行遍历
方法二: 通过数组元数的索引进行遍历
二、关联数组
定义关联数组:
申明关联数组变量
# declare -A ass_array1
# declare -A ass_array2
方法一: 一次赋一个值
数组名[索引]=变量值
# ass_array1[index1]=pear
# ass_array1[index2]=apple
# ass_array1[index3]=orange
# ass_array1[index4]=peach
方法二: 一次赋多个值
# ass_array2=([index1]=tom [index2]=jack [index3]=alice [index4]='bash shell')
查看数组:
# declare -A
declare -A ass_array1='([index4]="peach" [index1]="pear" [index2]="apple" [index3]="orange" )'
declare -A ass_array2='([index4]="bash shell" [index1]="tom" [index2]="jack" [index3]="alice" )'
访问数组元数:
# echo ${ass_array2[index2]} 访问数组中的第二个元数
# echo ${ass_array2[@]} 访问数组中所有元数 等同于 echo ${array1[*]}
# echo ${#ass_array2[@]} 获得数组元数的个数
# echo ${!ass_array2[@]} 获得数组元数的索引
遍历数组:
方法一: 通过数组元数的索引进行遍历
作业:
1. 使用关联数组统计文件/etc/passwd中用户使用的不同类型shell的数量
2. 使用关联数组按扩展名统计指定目录中文件的数量
========================================================