Progress Bars in Bash

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 a 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. Maybe, I’ll 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…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/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

Comments