Last Updated: December 24, 2017
·
8.381K
· abhishek_tamrakar

progress bars in bash scripts

While many of us often think of an easiest way of tracking an operation to be completed. Well, there are many tools out there that can help you doing that curl, pip, apt are few common examples of the tools which will display a fancy progress bar to let you know where the operation stands at present.

Life usually becomes tough when it comes to shell scripts, loops, conditions and command excutions specially. Lets understand what we need and then we will see few examples.

The need:
a. Something that takes/calculates no of tasks.
b. Something that displays completed and pending tasks.
c. Something that displays the percentile completion or eta.
d. Something that looks fancy too apart from #a to #d

Lets try something.

#!/bin/bash

# code is color code of the bar.
code=15

# function to calculate percentile completion
calcPer()
{
# declare a variable to count on
 local c=$1
# calculate percentile
 per=$(echo "scale=2;$c / $n * 100"|bc -l)
}

# start loop
# n=no of tasks 
# So, if you are processing a file n=no of lines in that file.
#
while [ $n -ge $i ]; do
 calcPer $i
 # call a small sleep to let people see the beauty of progress bar in action.
 sleep .5
 # print the color every time a task is done.
 printf "|\e[48;5;${code}m%${per%.*}s\e[31m${per%.*}"
 # make room for more, so escape the return. 
 printf '%s\e[0m%s\r' "%" "|" 
 # finally increament the counter for the next task in pipeline.
 echo $((i+=1)) >/dev/null
done
printf '\n'

Now lets check the output:
output