shell中打印进度条,需要用到tput、printf函数。
# tput row col 光标移到第row行第col列
# tput cols 获取窗口最大列数
# tput lines 获取窗口最大行书
# echo $LINENO 获取光标当前行号
function getprostr()
{
pchar=$1
ptotal=$2
outstr=""
numcol=`tput cols`
coltotal=$[$numcol/2/$ptotal]
for((i=1;i<=$coltotal;i++));
do
outstr="$outstr$pchar";
done
echo $outstr
}
function progressHead()
{
outstr=""
ptotal=$1
row=$2
str=`getprostr "-" $1`
for((i=1;i<=$ptotal;i++));
do
outstr="$outstr$str";
done
tput cup $row 0
echo "$outstr-"
}
function progress()
{
tput sc
pvalue=$1
ptotal=$2
row=$3
numcol=`tput cols`
gstr=`getprostr "=" $ptotal`
str="$gstr>"
if [ $pvalue == $ptotal ]; then
str="$gstr="
fi
barcol=$[($pvalue-1)*(${#str}-1)]
percent=$[$pvalue*100/ptotal]
tput cup $row $barcol
echo "$str"
tput cup $row $[$numcol/2]
echo "[$percent%]"
tput rc
}
clear
cols=`tput cols`
rows=`tput lines`
curline=$LINENO
progressHead 5 $[$LINENO-$curline-2]
progressrow=$[$LINENO-$curline-2]
#echo ""
progressHead 5 $[$LINENO-$curline-3]
progress 1 5 $progressrow
sleep 1
progress 2 5 $progressrow
sleep 1
progress 3 5 $progressrow
sleep 1
progress 4 5 $progressrow
sleep 1
progress 5 5 $progressrow
输出结果:
-----------------------------------------
========================================[100%]
-----------------------------------------
本文出自 “小何贝贝的技术空间” 博客,请务必保留此出处http://babyhe.blog.51cto.com/1104064/1612009
原文地址:http://babyhe.blog.51cto.com/1104064/1612009