# shell脚本编程实例--进度条，求和&平均值，斐波那契，改变字符串大小顺序

304人阅读 评论(0)

1. 字符串拼接
2. 依次打印

//依次打印
sum=0
for ((i=1; i<=100; i++))
do
if [ $i -eq 100 ];then echo -n "$i="
break
fi

echo -n "$i+" let sum+=i done echo$sum

//字符串拼接
sum=0
i=1
str=""
while test $i -le 100 do if [$i -eq 100 ];then
str=$str$i"="
break
fi

str=$str$i"+"
let sum+=i
let i++
done
echo $str$sum


function max_min()
{
max=$1 min=$1

for i in $@ do if test$max -lt $i ;then max=$i
fi
if [ $min -gt$i ]; then
min=$i fi done echo "max =$max"
echo "min = $min" } max_min$1 $2$3

str=''
arr=( "|" "/" "-" "\\")
count=0

for ((i=0; i<=100; i++))
do
printf "[%-100s][%d%%][%c]\r" "$str" "$i" "${arr[count]}" str=$str'#'
let count++
let count%=4
sleep 0.05
done

#echo ""
printf "\n"

function f()
{

local color='\033[45m'
local clear='\033[0m'
str=''
arr=( "|" "/" "-" "\\")
count=0

for ((i=0; i<=100; i++))
do
printf "$color[%s][%d%%][%c]$clear\r" "$str" "$i" "${arr[count]}" str=$str' '
let count++
let count%=4
sleep 0.05
done

#echo ""
printf "\n"
}

f  #调用函数


function Fib()
{
local first=1
local second=1
local third=$(($first+$second )) if [$1 -le 0 ];then
echo "$1 should be > 0" exit -1 elif [$1 -eq 1 -o $1 -eq 2 ];then echo 1 exit 0 fi i=3 while [$i -le $1 ] do let third=first+second let first=second let second=third let i++ done echo$third
}

function FibArr()
{
local arr=()
arr[1]=1
arr[2]=1

if [ $1 -le 0 ];then echo "$1 should be > 0"
exit -1
elif [ $1 -eq 1 -o$1 -eq 2 ];then
echo 1
exit 0
fi

i=3
while test $i -le$1
do
let arr[i]=arr[i-1]+arr[i-2]
let i++
done
echo ${arr[$1]}
}

function FibR()
{
if [ $1 -eq 1 -o$1 -eq 2 ];then
echo 1
exit 0
fi

pprev=$(($1-2 ))
prev=$(($1-1 ))

pprev_ret=$(FibR$pprev)
prev_ret=$(FibR$prev)
ret=$(( pprev_ret+prev_ret )) echo$ret
}

FibR $1 Fib$1

FibArr $1 求平均值，精度保证两位小数 if [$# -lt 3 ];then
echo "please input at least 3 arg"
exit -1
fi

max=$1 min=$1
sum=0
for i in $@ do #if [$max -lt $i ];then # max=$i
#fi

#if [ $min -gt$i ];then
#    min=$i #fi [$max -lt $i ] && max=$i
[ $min -gt$i ] && min=$i let sum+=i done echo "max=$max"
echo "min=$min" echo "sum=$sum"
avg= echo "scale=2; $sum /$#" | bc
echo "avg=$avg" 改变字符串 123abc456 123def456 改为 123ABC456 123DEF456 while read line do part1= echo$line | cut -c 1-3
part2= echo $line | cut -c 4-6 | tr '[a-z]' '[A-Z]'  part3= echo$line | cut -c 7-9
echo $part3$part2\$part1
done < file > newfile

0
0

个人资料
• 访问：44804次
• 积分：1391
• 等级：
• 排名：千里之外
• 原创：97篇
• 转载：11篇
• 译文：0篇
• 评论：11条
最新评论