Progress bars in Bash

posted 2009-08-10 08:20:31, link to this article

Today a colleague reminded me to dig up a script that I wrote some years ago to generate progress bars (or actually generic horizontal bar graphs) in Bash.

The script is, in this state, more like a proof of concept. It displays an bar that increments until full and then decrements again, this cycle is repeated forever. It should not be too hard to rewrite it to be used in something more useful.
I think it's also trivial to rewrite this to display vertical bar graphs as well. I might write a small Bash library to include in other scripts later, if and when I feel the need to. ;-)

The code of the script follows below, enjoy...

#!/bin/bash

# progress bar
# Hessel Schut, VPRO Automatisering, 2004-04-02

cols=$(tput cols)
bold=$(tput smso)
norm=$(tput rmso)

trap cleanup EXIT TERM INT

cleanup() {
        norm
        tput clear
        tput cnorm
        exit
}

hor_line() {
        for ((i=1; i < cols - 2; i++)); do
                echo -n '-'
        done
}

draw_frame() {
        tput cup 2 2; hor_line
        tput cup 3 1; echo -n '|'
        tput cup 3 ${cols}; echo -n '|'
        tput cup 4 2; hor_line
}

tput clear
tput civis
draw_frame

d=1; pos=2; plen=0
while [ == ]; do
        [ $d -eq 1 ] && face=${bold}
        tput cup 3 $pos
        echo -n ${face}' '
        face=${norm}
        sts='pos: '${pos}' dir: '${d}
        tput cup 1 1; echo -n ${norm}${sts}
        [ ${plen} -gt ${#sts} ] && for ((i=0; i < plen - ${#sts}; i++)); do
                echo -n ' '
        done
        plen=${#sts}
        ((pos += d))
        [ $pos -gt 2 ] && [ $pos -lt $((cols - 2 )) ] || ((d=-d))
done