您好,登录后才能下订单哦!
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。