Shell 数组变量
shell默认是普通数组 如果要定义关联数组 首先要先定义 declare -A 数组名
========================================================
普通数组:只能使用整数作为数组索引
关联数组:可以使用字符串作为数组索引
一、普通数组
定义数组:
方法一: 一次赋一个值
数组名[下标]=变量值
# 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) 第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[@]} 获得数组元数的索引
#!/bin/bash
while read line
do
hosts[i++]=$line
done </etc/hosts
echo "hosts first: ${hosts[0]}"
for i in ${!hosts[@]}
do
echo "$i: ${hosts[$i]}"
done
#!/bin/bash
OLD_IFS=$IFS
IFS=$'\n'
for line in `cat /etc/hosts`
do
hosts[i++]=$line
done
for i in ${!hosts[@]}
do
echo "$i : ${hosts[$i]}"
done
IFS=$OLD_IFS
统计男女人数
#!/bin/bash
declare -A sex
while read line
do
type=`echo $line | awk '{print $2}'`
let sex[$type]++
done < ./sex.txt
for i in ${!sex[@]}
do
echo "$i : ${sex[$i]}"
done
#!/bin/bash
declare -A shells
while read line
do
type=`echo $line | awk -F":" '{print $NF}'`
let shells[$type]++
done </etc/passwd
for i in ${!shells[@]}
do
echo "$i: ${shells[$i]}"
done
本文介绍了Shell数组变量,包括普通数组和关联数组。普通数组只能用整数作索引,关联数组可用字符串作索引。文中详细说明了两种数组的定义方法,有一次赋一个值和一次赋多个值两种方式,还介绍了查看数组和访问数组元素的操作。
608





