Wednesday, June 8, 2011

Create a shell script to display progress meter like wget's meter style

The following is a shell script to display progress meter like wget's meter style
The shell script output
$./meter.sh 
27 % |======================>                                                                   |
The shell script source code
$cat ./meter.sh
#!/bin/ksh
#Given start number and end number, display  progress meter and percentage like wget's style
start=1
#end=333
end=33
scale=$(($end/100.0))
for i in {$start..$end}
do
m1=$(($i / $scale)); m2=$(( ($end - $i ) / $scale ))
integer m1; integer m2
#fill 2 segments of variable length  with zeros
str=$( printf "%0${m1}d %s %0${m2}d\n"   0 ">" 0  ) 
str="|$str|"
#replace first segment zeros with '=' 2nd segment zeros with space then re-join
str1=$(echo $str | awk -F' > ' '{ print $1 }'); str1=${str1//0/=}
str2=$(echo $str | awk -F' > ' '{ print $2 }'); str2=${str2//0/' '}
str="${str1}>${str2}"
pct=$(($i * 100 / $end ))
#Beautify the final loop 
[ $i -eq $end ] && str=$(echo $str | sed -e 's/ /=/g' -e 's/>/=/g' -e 's/0/=/g' )
print -n " \\r ${pct} % $str "
sleep 1
done
printf "\n"

No comments:

Post a Comment