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
二、寫一個腳本,生成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
三、寫一個腳本,能從全部同窗中隨機挑選一個同窗回答問題;進一步地:可接受一個參數,作爲要挑選的同窗的個數;函數
#!/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!"
執行效果測試
進一步的可接受一個參數,作爲要挑選的同窗的個數;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
最後:分享幾個取隨機數的原理
高級Bash腳本編程指南(取隨機數)
http://www.21andy.com/manual/advanced-bash-scripting-guide/randomvar.html
Bash中生成指定範圍的隨機數
http://blog.csdn.net/robertsong2004/article/details/38712227