1...100的求和
非递归:
#!/bin/bash
readnum
count=1
sum=0
val=""
ret=""
while[$count-le$num]
do
if[$count-eq$num];then
val=$count
else
val=${count}‘+‘
fi
letsum+=count
letcount++
ret=${ret}${val}
done
echo${ret}‘=‘$sum
递归:
#!/bin/bash
readnum
functionadd(){
localval=$1
localcount=0
localsum=0
localnum=$val
if[$val-eq1];then
echo1
return
fi
arr=$count1+$val
letval--
letcount=$(add$val)
letsum=$count+$num
echo$sum
}
ret=$(add$num)
echo$ret
结果:
[[emailprotected] 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
readname
max=0
min=0
count=0
whilereadline
do
if[$count-eq1];then
min=$line
fi
((count++))
if[$max-lt$line];then
max=$line
fi
if[$min-gt$line];then
min=$line
fi
done
echo"max:"$max"min:"$min
斐波那契数列求和
非递归
#!/bin/bash
readnum
fib_val[0]=1
fib_val[1]=1
count=0
functionfib(){
localval=$1
while[$count-lt$val]
do
letfib_val[${count}+2]=${fib_val[${count}+1]}+${fib_val[$count]}
letcount++
done
}
fib$num
echo${fib_val[$count]}
递归:
#!/bin/bash
readnum
functionfib(){
localval=$1
localnum1=0
localnum2=0
if[$val-eq0-o$val-eq1];then
echo1
return
fi
letval--
num1=$(fib$val)
letval--
num2=$(fib$val)
letsum=$num1+$num2
echo$sum
}
结果:
[[emailprotected] test6_19]$ ./fib.sh
1
1
[[emailprotected] test6_19]$ ./fib.sh
2
2
[[emailprotected] test6_19]$ ./fib.sh
11
144
字符串截取的应用
#!/bin/bash
readname
str1=""
str2=""
str3=""
str=""
whilereadline
do
str1=$(echo$line|cut-c1-3)
str2=$(echo$line|cut-c4-6|tr‘[a-z]‘‘[A-Z]‘)
str3=$(echo$line|cut-c7-9)
str="${str3}""${str2}""${str1}"
echo$str
donefile_bak
结果:
[[emailprotected] test6_19]$ cat file1
123abc789
456def789
364rgy532
278bsy682
[[emailprotected] test6_19]$ vim string.sh
[[emailprotected] test6_19]$ ./string.sh
file1
[[emailprotected] test6_19]$ cat file_bak
789ABC123
789DEF456
532RGY364
682BSY278
时间: 06-19