内容概要
一、数组定义方法
方法一
数组名=(value0 value1 value2 …)
方法二
数组名=([0]=value [1]=value [2]=value …)
方法三
列表名=“value0 value1 value2 …”
数组名=($列表名)
方法四
数组名[0]=“value”
数组名[1]=“value”
…
二、数组查看方法
查看数组内容
可以使用:echo ${数组名[*]} 或者 echo ${数组名[@]}
查看数组内元素个数
可以使用:echo ${#数组名[*]} 或者 echo ${#数组名[@]}
遍历数组内容
for i in ${数组名[*]}
do
echo $i
done
三、数组操作
数组切片
[root@localhost /etc/test2#] arr2=(1 2 3 4 5 6 7)
[root@localhost /etc/test2#] echo ${arr2[*]}
1 2 3 4 5 6 7
[root@localhost /etc/test2#] echo ${arr2[*]:2:3} //截取数组下标为2的元素,长度为3个元素
3 4 5
[root@localhost /etc/test2#]
数组替换
临时替换
[root@localhost /etc/test2#] echo ${arr2[*]}
1 2 3 4 5 6 7
[root@localhost /etc/test2#] echo ${arr2[*]/5/100}
1 2 3 4 100 6 7
永久替换
[root@localhost /etc/test2#] echo ${arr2[*]}
1 2 3 4 5 6 7
[root@localhost /etc/test2#] arr2=(${arr2[*]/5/100})
[root@localhost /etc/test2#] echo ${arr2[*]}
1 2 3 4 100 6 7
删除数组
删除数组内某一个元素
[root@localhost /etc/test2#] echo ${arr2[*]}
1 2 3 4 5 6 7
[root@localhost /etc/test2#] unset arr2[4]
[root@localhost /etc/test2#] echo ${arr2[*]}
1 2 3 4 6 7
删除整个数组
[root@localhost /etc/test2#] arr2=(1 2 3 4 5 6 7)
[root@localhost /etc/test2#] echo ${arr2[*]}
1 2 3 4 5 6 7
[root@localhost /etc/test2#] unset arr2[*]
[root@localhost /etc/test2#] echo ${arr2[*]}
[root@localhost /etc/test2#]
数组追加元素
方法一
数组名 [下标] = value
方法二
数组名 [${#数组名[*]}]=value
方法三
数组名+=(value1 value2 …)
向函数传数组参数
如果将数组变量作为函数参数,函数只会取数组内第一个值
分为四个步骤:
1、先将数组拆分成列表 ${arr[@]}
2、函数通过$@获取之前将数组拆分成的列表 $@
3、在函数中重新把列表定义成数组 newarr=($@0)
4、对新的数组进行进一步的处理,再echo 输出
从函数返回数组
#!/bin/bash
#从函数返回数组
#用于求数组中所有元素值的累加和
test1 () {
newarr=($@)
arrlist=${newarr[*]}
for i in $arrlist
do
sum=$[$sum + $i]
done
echo $sum
}
#用于把原数组中所有的元素值*2后输出,后生成新数组
test2 () {
newarr1=($@)
length=${#newarr1[*]}
for ((j=0;j<=length-1;j++))
do
newarr1[$j]=$[${newarr1[j]} * 2]
done
echo ${newarr1[*]}
}
#####main######
arr=(10 20 30 40 50 60)
echo "原数组的列表为:${arr[*]}"
res1=`test1 ${arr[*]}`
echo "test1新数组的累加和为:${res1[*]}"
res2=`test2 ${arr[*]}`
echo "test2新数组的乘2后的值:${res2[*]}"
四、数组排序
冒泡排序
冒泡排序的基本思路:冒泡排序的基本思想是对比相邻的两个元素值,如果满足条件就交换元素值,把较小的元素移动到数组前面,把大的元素移动到数组后面(也就是交换两个元素的位置),这样较小的元素就像气泡一样从底部上升到顶部。
#!/bin/bash
arr=(15 13 57 45 79 17)
echo "原来数组的顺序为:${arr[*]}"
length=${#arr[*]}
for ((i=1;i<$length;i++))
do
for ((j=0;j<$length-$i;j++))
do
first=${arr[$j]}
k=$[$j + 1]
second=${arr[$k]}
if [ $first -gt $second ];then
temp=${arr[$j]}
arr[$j]=$second
arr[$k]=$temp
fi
done
done
echo "排序后的新的数组的顺序为:${arr[*]}"
手动输入数组:
选择排序
#!/bin/bash
arr=(10 5 7 3 2 9)
length=${#arr[*]}
echo "原始数组的顺序为:${arr[*]}"
for ((i=1;i<$length;i++))
do
index=0
for ((j=1;j<=$length-$i;j++))
do
if [ ${arr[$j]} -gt ${arr[$index]} ];then
index=$j
fi
done
last=$[$length - $i]
temp=${arr[$last]}
arr[$last]=${arr[$index]}
arr[$index]=$temp
done
echo "排序后的数组为:${arr[*]}"
反转排序
#!/bin/bash
arr=(10 20 30 40 50 60)
length=${#arr[*]}
echo "原始数组的顺序为:${arr[*]}"
for ((i=0;i<$length/2;i++))
do
temp=${arr[$i]}
arr[$i]=${arr[$length-1-$i]}
arr[$length-1-$i]=$temp
done
echo "排序后的数组顺序为:${arr[*]}"