Shell動態(tài)生成數(shù)組的多種方法
如果對linux shell 數(shù)組不是很熟悉的話,請看上一篇文章:linux shell 數(shù)組建立及使用技巧 ,這篇文章主要講是動態(tài)生成數(shù)組系列。方法應(yīng)該很多,我這里主要以一個求和計算的題目為例進行分析。
題目:請用linux shell 寫一段腳本,實現(xiàn)從1..1000中所有偶數(shù)的和值。
方法一:
通過while 循環(huán)得到需要的結(jié)果:
start=1; total=0; while [ $start -le 1000 ];do [[ $(($start%2)) == 0 ]]&&total=$(($total+$start)); start=$(($start+1)); done; echo $total; [chengmo@centos5 ~]$ start=1;total=0;while [ $start -le 1000 ];do [[ $(($start%2)) == 0 ]]&&total=$(($total+$start)); start=$(($start+1));done;echo $total; 250500
以上運行結(jié)果是:249500,在linux shell 中,”;”作為命令行分隔符。如果大家對于$(()) 運算符號不是很理解,可以查看:linux shell 實現(xiàn) 四則運算(整數(shù)及浮點) 簡單方法 ,如果對于:[[]] [] 符號,可以參考另外一篇文章linux shell 邏輯運算符、邏輯表達式詳解。
方法二:
通過 for 循環(huán)得到結(jié)果:
start=0; total=0; for i in $(seq $start 2 1000); do total=$(($total+$i)); done; echo $total; [chengmo@centos5 ~]$ start=0;total=0;for i in $(seq $start 2 1000); do total=$(($total+$i));done;echo $total; 250500
上面語句已經(jīng)代碼方面明顯優(yōu)于方法一,而且性能方面表現(xiàn)也很好。下面比較就可以發(fā)現(xiàn):
比較性能:
[chengmo@centos5 ~]$ time (start=0;total=0;for i in $(seq $start 2 1000); do total=$(($total+$i));done;echo $total;) 250500 real 0m0.016s user 0m0.012s sys 0m0.003s [chengmo@centos5 ~]$ time (start=1;total=0;while [ $start -le 1000 ];do [[ $(($start%2)) == 0 ]]&&total=$(($total+$start)); start=$(($start+1));done;echo $total;) 250500 real 0m0.073s user 0m0.069s sys 0m0.004s
方法一耗時 是方法二的 6倍!
seq 使用:
seq [OPTION]... LAST seq [OPTION]... FIRST LAST seq [OPTION]... FIRST INCREMENT LAST [chengmo@centos5 ~]$ seq 1000 ‘起始默認是 1,間隔默認也是1 [chengmo@centos5 ~]$seq 2 1000 ‘間隔默認是1 [chengmo@centos5 ~]$seq 1 3 10 '從1開始,到10 間隔為3 結(jié)果是:1 4 7 10 說明:默認間隔是“空格” 如果想換成其它的可以帶參數(shù):-s [chengmo@centos5 ~]$seq -s'#' 1 3 10 1#4#7#10
應(yīng)用技巧:
生成連續(xù)數(shù)組系列:
[chengmo@centos5 ~]$ a=($(seq 1 3 10))
[chengmo@centos5 ~]$ echo ${a[1]}
4
[chengmo@centos5 ~]$ echo ${a[@]}
1 4 7 10
生成連續(xù)相同字符:
[chengmo@centos5 ~]$ seq -s '#' 30 | sed -e 's/[0-9]*//g' #############################
上面例子:通過加入間隔字符‘#'后,替換掉數(shù)字, 生成連續(xù)相同字符'#',這個在以后書寫中還是有不少幫助。
相關(guān)文章
完美解決ntp的錯誤問題no server suitable for synchronization fo
下面小編就為大家?guī)硪黄昝澜鉀Qntp的錯誤問題no server suitable for synchronization fo。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03
使用shell腳本每天對MySQL多個數(shù)據(jù)庫自動備份的講解
今天小編就為大家分享一篇關(guān)于使用shell腳本每天對MySQL多個數(shù)據(jù)庫自動備份的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03

