标签:shell
一、用shell脚本实现进度条
#!/bin/bash function proc() 4 { 5 count=0 6 bar="" 7 lable=("|" "/" "-" "\\") 8 while [ $count -le 100 ] 9 do 10 let index=count%4 11 printf "[\033[1m\033[1;34m%-101s\033[0m] [%d%%] [%c]\r" "$bar" "$count" "${lable[$index]}" 12 bar=${bar}‘#‘ 13 (( count++ )) 14 sleep 0.05 15 done 16 # printf "\n" 17 } 18 proc
二、求1-100的和(非递归)
#!/bin/bash 20 sum=0 21 str=" " 22 for i in {1..100} 23 do 24 let sum+=i 25 [ $i -eq 100 ] && { 26 str=${str}${i} 27 break 28 } 29 str=${str}${i}‘+‘ 30 #((sum=sum+i)) 31 done 32 #echo $sum 33 echo "$str=$sum"
三、1-100的求和(递归)
#!/bin/bash function sum() 4 { 5 local val=$1 6 local res 7 if [ $val -eq 1 ];then 8 echo 1 9 return 10 fi 11 12 local tem=$val 13 let tem-- 14 local tem1=0 15 tem1=$(sum $tem) 16 let res=$tem1+$val 17 echo $res 18 } 19 sum 100
四、求一个文件中数的最大值、最小值、平均值
file文件中的三个数:100,200,300
1 #!/bin/bash 2 count=0 3 while read line 4 do 5 let ++count 6 [ $count -eq 1 ] && min=$line && max=$line 7 let sum+=$line 8 [ $line -gt $max ] && max=$line 9 [ $line -lt $min ] && min=$line 10 done <file 11 echo "max: ${max}" 12 echo "min: ${min}" 13 printf "argv: " 14 echo "base=10;scale=2; 15 ${sum}/${count}" | bc
五、斐波那契数列(非递归)
54 #!/bin/bash 55 56 function fib() 57 { 58 read val 59 fib_arr[1]=1 60 fib_arr[2]=1 61 local count=0 62 while [ $count -le $val ] 63 do 64 let fib_arr[$count+2]=fib_arr[$count+1]+fib_arr[$count] 65 ((count++)) 66 done 67 echo ${fib_arr[$val]} 68 } 69 fib
六、斐波那契(递归)
#!/bin/bash function fib() 76 { 77 local val=$1 78 local fiv_val1=0 79 local fiv_val2=0 80 local fiv_curr=0 81 if [ $1 -lt 3 ];then 82 echo 1 83 return 84 fi 85 let val-- 86 fiv_val1=$( fib $val ) 87 let val-- 88 fiv_val2=$( fib $val ) 89 let fiv_curr=$fiv_val1+$fiv_val2 90 echo $fiv_curr 91 } 92 ret=$(fib $val) 93 echo "$ret"
七、将一个问价中的字符串转换:例如:"123abc456"->"456ABC123"
file文件中是“123abc456”转换成“456ABC123”
#!/bin/bash 21 read name 22 23 while read line 24 do 25 str1=$(echo $line | cut -c 1-3) 26 str2=$(echo $line | cut -c 4-6 | tr ‘[a-z]‘ ‘[A-Z]‘) 27 str3=$(echo $line | cut -c 7-9) 28 echo ${str3}${str2}${str1} 29 done<$name >${name}_bak 30 function main() 31 { 32 read target 33 sum $target 34 } 35 main
标签:shell
原文地址:http://9195095.blog.51cto.com/9185095/1792660