脚本编程类(数组练习)

SHELL整理汇总:html


脚本编程练习编程

一、写一个脚本:定义一个数组,数组元素为/var/log目录下全部以.log结尾的文件的名字;显示每一个文件的行数;数组

#!/bin/bash

declare -a files
files=(/var/log/*.log)
for i in `seq 0 $[${#files[@]}-1]`;
    do wc -l ${files[$i]}
done

执行结果:bash

wKioL1ZENM3i0yT-AAA5TFCdBmQ915.png


二、写一个脚本,生成10个随机数,并按从小到大进行排序;dom

#!/bin/bash 

for ((i=0;i<10;i++));do
	rand[$i]=$RANDOM
done

for ((i=0;i<10;i++));
do
    for ((j=9;j>i;j--));
    do
	if [[ ${rand[j]} -lt ${rand[j-1]} ]]
	then 
	    tmp=${rand[j]}
	    rand[j]=${rand[j-1]}
	    rand[j-1]=$tmp
	fi
    done
done

echo ${rand[@]}

执行结果:
ide

wKioL1ZESLWimyKsAAAyk39qyTI358.png


三、写一个脚本,能从全部同窗中随机挑选一个同窗回答问题;进一步地:可接受一个参数,作为要挑选的同窗的个数;函数

#!/bin/bash
echo "+------------------------------+"
echo "| Please Input Students' Name  |"
echo "| Name shouldn't include space |"
echo "+------------------------------+"
  
read -a student
random=$((RANDOM % ${#student[@]}))
echo "Please ${student[$random]} answer the Question!"

执行效果测试

wKioL1ZEguLhYQjWAABPsJQcyD8478.png


进一步的可接受一个参数,作为要挑选的同窗的个数;ui

#!/bin/bash

echo "+------------------------------+"
echo "| Please Input Students' Name  |"
echo "| Name shouldn't include space |"
echo "+------------------------------+"

read -a student
read -p "Please Input the number of students to answer quest    ion" num
if [ $num -gt ${#student[@]} ];then
    echo "Error!"
    exit
fi

echo "The following students to answer:"
for ((i=0;i<num;i++));
    do random=$((RANDOM % ${#student[@]}))
       echo ${student[$random]}
       student[$random]=${student[${#student[@]}-1]}
       unset student[${#student[@]}-1]
   done

原理:每次取出一名同窗后,假设该同窗的数组索引为a,将原来数组中最后索引的数组元素值赋值给 array[a],同时删除最后一个数组元素,这样每次抽出同窗后,余下的新数组的元素值就不会重复了。spa

wKiom1ZEhd2honGtAAA9tGT4wYs432.png


最后:分享几个取随机数的原理


  1. 高级Bash脚本编程指南(取随机数)

    http://www.21andy.com/manual/advanced-bash-scripting-guide/randomvar.html

  2. Bash中生成指定范围的随机数

    http://blog.csdn.net/robertsong2004/article/details/38712227

相关文章
相关标签/搜索