1、計算1+2+3+4....+100的結果:
函數遞歸法:(參數從命令行傳入)
sum=0
function fun
{
if [ $1 -eq 0 ];then
echo $sum
else
let sum+=$1
fun $(($1-1))
fi
}
fun $1
2、編寫簡單進度條(+配色)
#!/bin/bash
bar=''
i=0
f=('|' '/' '-' '\\')
while [ $i -le 100 ]
do
let index=i%4
#printf "[%d%%][\e[47;46;1m%-100s\e[0m]][%c]\r" $i "$bar" "${f[$index]}"
printf "[%d%%][\033[47;46;5m%-100s\033[0m][%c]\r" $i "$bar" "${f[$index]}"
bar=${bar}'#'
let i++
sleep 0.1
done
printf "\n"
結果:
3、 傳入至少三個數字參數到腳本file,並計算出最大,最小,平均值。需要判斷
傳入的數字是否足夠,否則輸出警告信息。平均值保留兩位⼩數。
如執行./file 3 4 6 5,輸出結果如下:
max is 6
min is 3
4.50
#!/bin/bash
sum=0
if [ $# -lt 3 ] ;then
echo "PLease input 3 numbers"
else
min=$1
max=$1
for i in $@
do
if [ $i -lt $min ] ;then
min=$i
elif [ $i -gt $max ] ;then
max=$i
else
:
fi
let sum+=$i
done
printf "max is %d\n" $max
printf "min is %d\n" $min
#echo $sum
arr=$(($sum/$#))
echo "ibase=10;scale=2;$sum/$#" | bc #ibase控制輸出顯示的進制 scale 控制精度
fi
4、求斐波那契數列的第n個值
n通過命令行參數傳入
#!/bin/bash
sum=0
i=$1
first=1
second=1
third=2
if [ $1 -eq 1 ] || [ $1 -eq 2 ];then
sum=1
echo $sum
exit 1
fi
while [ $i -ge 2 ]
do
((third=first+second))
#echo $third
first=$second
#echo $first
second=$third
#echo $second
let i--
done
echo $third
5、 文件內容如下:
123abc456
456def123
567abc789
789def567
要求從文件中讀取內容並輸出:
456ABC123
123DEF456
789ABC567
567DEF789
#!/bin/bash
while read line
do
typeset -u b
b=${line:3:3}
a=${line:0-3:3}
c=${line:0:3}
#echo $b
echo ${a}${b}${c}
done <1.txt