数组(Array)是一个由若干同类型变量组成的集合,引用这些变量时可用同一名字。数组均由连续的存储单元组成,最低地址对应于数组的第一个元素,最高地址对应于最后一个元素。bash Shell只支持一维数组,数组从0开始标号,以array[x]表示数组元素,那么,array[0]就表示array数组的第1个元素、array[1]表示array数组的第2个元素、array[x]表示array数组的第x+1个元素。
bash Shell取得数组值(即引用一个数组元素)的命令格式是:
${array[x]}
#引用array数组标号为x的值,$符号后面的大括号必不可少
定义
declare -a city # city为数组名
赋值
#!/bin/bash
city[0]=Nanjing
city[1]=Beijing
city[9]=Melbourne
city[15]=NewYork
echo "city[0]=${city[0]}"
echo "city[1]=${city[1]}"
echo "city[9]=${city[9]}"
echo "city[15]=${city[15]}"
echo "city[2]=${city[2]}"
echo "city[10]=${city[10]}"
还可以用小括号将一组值赋给数组
city=(Nanjing Beijing Melbourne NewYork)
city=(Nanjing [10]=Atlanta Massachusetts Marseilles)
city=([2]=Nanjing [10]=Atlanta [1]=Massachusetts [5]=Marseilles)
array[@]
和array[*]
都表示了array
数组的所有元素
for i in ${city[@]} #将@替换为*亦可
do
echo $i
done
操作
数组字符串所有操作都是针对所有数组元素逐个进行的
切片
city=(Nanjing Atlanta Massachusetts Marseilles)
echo "Extracting Substring"
echo ${city[*]:0}
echo ${city[*]:1}
echo ${city[*]:3}
echo ${city[*]:0:2} 从编号为0 的开始 ,长度为2
echo
剔除
echo "Removing Substring"
echo ${city[*]#M*a} //按最小长度删除
echo ${city[*]##M*a} //按最大长度删除
echo
echo "Replcing Substring"
echo ${city[*]/M*s/Year}
echo ${city[*]//M*s/Year
用read命令从stdin读取一系列的值
read -a array可以将读到的值存储到array数组
echo "What city have you been arrived?"
echo "The input should be separated from each other by a SPACE"
read -a arrivedcity
echo
for i in "${arrivedcity[@]}"
do
echo "$i"
done
删除元素
echo "The length of this array is ${#arrivedcity[@]}."
echo "Executing UNSET operation........."
unset arrivedcity[1] //删除第2个城市
echo "The length of this array is ${#arrivedcity[@]}."
echo "Executing UNSET operation........."
unset arrivedcity //删除所有的城市
echo "The length of this array is ${#arrivedcity[@]}."
数组连接
将多个数组合并到一个数组
#定义并赋值
city=(Beijing Nanjing Shanghai)
person=(Cai [5]=Wu Tang)
方法一
declare -a combine //声明一个数组,其名为combine
combine=(${city[@]} ${person[@]})
#combine=${city[@]}${person[@]}
element_count=${#combine[@]} //获取数组长度
index=0
while [ "$index" -lt "$element_count" ]
do
echo "Element[$index]=${combine[$index]}"
let "index=$index+1"
done
echo
unset combine //删除数组
方法二
combine[0]=${city[@]}
combine[1]=${person[@]}
element_count=${#combine[@]}
index=0
while [ "$index" -lt "$element_count" ]
do
echo "Element[$index]=${combine[$index]}"
let "index=$index+1"
done
echo
方法三
declare -a subcombine=${combine[1]} //声明一个数组,其值为${combine[1]}
element_count=${#subcombine[@]}
index=0
while [ "$index" -lt "$element_count" ]
do
echo "Element[$index]=${subcombine[$index]}"
let "index=$index+1"
done