数组练习
1、使用数组和循环实现冒泡排序
#!/bin/bash
#定义一个数组arr
arr=(4 5 2 1 3 0)
#循环比较的轮数
for ((round=0;round<${#arr[*]}-1;round++))
do
#每轮比较的次数为长度-1-轮数
for ((count=0;count<${#arr[*]}-1-round;count++))
do
#比较前一个数和后一个数的大小
if [ ${arr[count]} -gt ${arr[count+1]} ];then
#交换两个数
temp=${arr[count]}
arr[count]=${arr[count+1]}
arr[count+1]=$temp
fi
done
echo ${arr[*]}
done
2、将冒泡排序的代码重构为2个函数,2个关系是a函数调用b函数
vim mppx2.sh
#!/bin/bash
function pk {
for ((count=0; count<${#arr[*]}-1-round; count++))
do
if [ ${arr[count]} -gt ${arr[count+1]} ];then
temp=${arr[count]}
arr[count]=${arr[count+1]}
arr[count+1]=$temp
fi
done
}
function rou {
for ((round=0; round<${#arr[*]}-1; round++))
do
pk
done
echo ${arr[*]}
}
arr=(5 2 8 1 9)
rou "${arr[@]}"
自定义数组参数:
#!/bin/bash
function pk {
for ((count=0; count<${#arr[*]}-1-round; count++))
do
if [ ${arr[count]} -gt ${arr[count+1]} ];then
temp=${arr[count]}
arr[count]=${arr[count+1]}
arr[count+1]=$temp
fi
done
}
function rou {
for ((round=0; round<${#arr[*]}-1; round++))
do
pk
done
echo ${arr[*]}
}
arr=($1)
rou "${arr[@]}"
3、声明一个存储的全整数数组,对其中的每一个值进行+10处理
#!/bin/bash
#定义一个数组
arr=(5 2 7 1 3)
#遍历数组中的每个数
for ((count=0; count<${#arr[*]}; count++))
do
#将每个数加10
arr[count]=$(echo "${arr[count]}+10"|bc)
done
echo ${arr[*]}
4、对硬盘使用空间占比的排序
#!/bin/bash
#查看磁盘使用空间占比,并提取各个数据
mes=$( echo -n $(df -h|awk '{print $5}') )
shuzu=$(echo ${mes#*%}|tr -d '%')
arr=($shuzu)
function pk {
for ((count=0; count<${#arr[*]}-1-round; count++))
do
if [ ${arr[count]} -gt ${arr[count+1]} ];then
temp=${arr[count]}
arr[count]=${arr[count+1]}
arr[count+1]=$temp
fi
done
}
function rou {
for ((round=0; round<${#arr[*]}-1; round++))
do
pk
done
echo ${arr[*]}
}
rou "${arr[@]}"
5、对当前目录的文件大小进行排序
#!/bin/bash
#提取文件大小
fsz=$( echo -n $(ls -l|awk '{print $5}') )
arr=("$fsz")
function pk {
for ((count=0; count<${#arr[*]}-1-round; count++))
do
if [ ${arr[count]} -gt ${arr[count+1]} ];then
temp=${arr[count]}
arr[count]=${arr[count+1]}
arr[count+1]=$temp
fi
done
}
function rou {
for ((round=0; round<${#arr[*]}-1; round++))
do
pk
done
echo ${arr[*]}
}
rou "${arr[@]}"
或者
bash mppx2.sh "$(echo -n $(ls -l|awk '{print $5}'))"