The summation of 1...100
Non-recursive: #!/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 recursion: #!/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= $count 1+$ val let val-- let count=$ ( add $ val ) let sum= $count + $num echo $sum } ret=$ (add $num) echo $ret
Results:
[Email protected] 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
Maximum minimum value of the number in a file
#!/bin/bash Read Namemax=0min=0count=0while read Linedo 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 < $n Ameecho "Max:" $max "min:" $min
The Fibonacci sequence sums
Non-recursive #!/bin/bashread numfib_val[0]=1fib_val[1]=1count=0function 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 $numecho ${fib_val[$count]} Recursion: #!/bin/bashread numfunction 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= $num 1+ $num 2 echo $sum}
Results:
[Email protected] test6_19]$./fib.sh
1
1
[Email protected] test6_19]$./fib.sh
2
2
[Email protected] test6_19]$./fib.sh
11
144
Application of String interception
#!/bin/bashread namestr1= "" str2= "" str3= "" str= "" while read Linedo 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 < $na Me >file_bak
Results:
[email protected] test6_19]$ cat File1
123abc789
456def789
364rgy532
278bsy682
[Email protected] test6_19]$ vim string.sh
[Email protected] test6_19]$./string.sh
File1
[email protected] test6_19]$ cat File_bak
789abc123
789def456
532rgy364
682bsy278
This article is from the "Small Town Moss" blog, please make sure to keep this source http://fengbaoli.blog.51cto.com/10538178/1790844
Shell Script Application Applet