SHELL整理彙總:
[9-13]Shell系列1——基本概念
[9-13]Shell系列2——變量基礎
[9-13]Shell系列3——分支結構if與case語句
[9-13]Shell系列4——循環結構for、while、until及跳出循環
[9-13]Shell系列5——條件測試和運算符
[9-13]Shell系列6——取算數運算數值
[9-13]Shell系列7——函數及參數傳遞
[9-13]Shell系列8——數組
腳本編程練習
1、寫一個腳本:定義一個數組,數組元素爲/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
執行結果:
2、寫一個腳本,生成10個隨機數,並按從小到大進行排序;
#!/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[@]}
執行結果:
3、寫一個腳本,能從所有同學中隨機挑選一個同學回答問題;進一步地:可接受一個參數,做爲要挑選的同學的個數;
#!/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!"
執行效果
進一步的可接受一個參數,做爲要挑選的同學的個數;
#!/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],同時刪除最後一個數組元素,這樣每次抽出同學後,餘下的新數組的元素值就不會重複了。
最後:分享幾個取隨機數的原理
高級Bash腳本編程指南(取隨機數)
http://www.21andy.com/manual/advanced-bash-scripting-guide/randomvar.html
Bash中生成指定範圍的隨機數
http://blog.csdn.net/robertsong2004/article/details/38712227