腳本編程類(數組練習)

SHELL整理彙總:


腳本編程練習

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

執行結果:

wKioL1ZENM3i0yT-AAA5TFCdBmQ915.png


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[@]}

執行結果:

wKioL1ZESLWimyKsAAAyk39qyTI358.png


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!"

執行效果

wKioL1ZEguLhYQjWAABPsJQcyD8478.png


進一步的可接受一個參數,做爲要挑選的同學的個數;

#!/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],同時刪除最後一個數組元素,這樣每次抽出同學後,餘下的新數組的元素值就不會重複了。

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章