您好,登錄后才能下訂單哦!
1...100的求和
非遞歸: #!/bin/bash read num count=1 sum=0 val="" ret="" while [ $count -le $num ] do if [ $count -eq $num ];then val=$count else val=${count}'+' fi let sum+=count let count++ ret=${ret}${val} done echo ${ret}'='$sum 遞歸: #!/bin/bash read num function add(){ local val=$1 local count=0 local sum=0 local num=$val if [ $val -eq 1 ];then echo 1 return fi arr=$count1+$val let val-- let count=$( add $val ) let sum=$count+$num echo $sum } ret=$(add $num) echo $ret
結果:
[fbl@www test6_19]$ ./add.sh
100
1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50+51+52+53+54+55+56+57+58+59+60+61+62+63+64+65+66+67+68+69+70+71+72+73+74+75+76+77+78+79+80+81+82+83+84+85+86+87+88+89+90+91+92+93+94+95+96+97+98+99+100=5050
求一個文件中數的最大最小值
#!/bin/bash read name max=0 min=0 count=0 while read line do if [ $count -eq 1 ];then min=$line fi (( count++ )) if [ $max -lt $line ];then max=$line fi if [ $min -gt $line ];then min=$line fi done <$name echo "max: "$max "min: "$min
斐波那契數列求和
非遞歸 #!/bin/bash read num fib_val[0]=1 fib_val[1]=1 count=0 function fib(){ local val=$1 while [ $count -lt $val ] do let fib_val[${count}+2]=${fib_val[${count}+1]}+${fib_val[$count]} let count++ done } fib $num echo ${fib_val[$count]} 遞歸: #!/bin/bash read num function fib(){ local val=$1 local num1=0 local num2=0 if [ $val -eq 0 -o $val -eq 1 ];then echo 1 return fi let val-- num1=$( fib $val ) let val-- num2=$( fib $val ) let sum=$num1+$num2 echo $sum }
結果:
[fbl@www test6_19]$ ./fib.sh
1
1
[fbl@www test6_19]$ ./fib.sh
2
2
[fbl@www test6_19]$ ./fib.sh
11
144
字符串截取的應用
#!/bin/bash read name str1="" str2="" str3="" str="" while read line do str1=$(echo $line|cut -c 1-3) str2=$(echo $line|cut -c 4-6 |tr '[a-z]' '[A-Z]') str3=$(echo $line|cut -c 7-9) str="${str3}""${str2}""${str1}" echo $str done <$name >file_bak
結果:
[fbl@www test6_19]$ cat file1
123abc789
456def789
364rgy532
278bsy682
[fbl@www test6_19]$ vim string.sh
[fbl@www test6_19]$ ./string.sh
file1
[fbl@www test6_19]$ cat file_bak
789ABC123
789DEF456
532RGY364
682BSY278
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。