Bash Loading Bar

2013-08-22

Another round of more fancy Bash graphics. This time a loading bar.

~~~~
function __loadingbar__ () {
        declare -i j k l len
        len=${1}
        [[ ${len} -eq 0 ]] && echo "" && return 0
        [[ ! ${i} || ${i} -eq $(( ${len} + 2 )) ]] && i=0
        j=0
        l=$(( ${i} + 1 ))
        while [[ ${j} -lt $(( ${i} - 1 )) ]]; do
                echo -n "-"
                j=$[${j}+1]
        done
        [[ ${i} -eq 0 || ${i} -eq $(( ${len} + 1 )) ]] && echo -n ">" || echo -n ">>"
        while [[ ${l} -le ${len} ]]; do
                echo -n "-"
                l=$[${l}+1]
        done
        for ((k=0; k <= ${len}; k++)); do
                echo -ne "\b"
        done
        i=$[${i}+1]
        sleep 0.1
}

e=0
## Any whitespace on the same line can go here
echo -ne "\n\t\t"
while [[ ${e} -le 100 ]]; do
	__loadingbar__ 10
done
## This just prints a blank line and is a good way to indicate the bar has been terminated
__loadingbar__ 0
echo "Oh, I've loaded!"
~~~~
All the above does is display the loading bar for 10 seconds and then echos "Oh, I've loaded!". But the focus is on the bar itself.

Rather than using clear (which would be the easy way), I've opted to backspace the whole line each time instead. This has two major advantages:

1) Doesn't spam your terminal.
2) Doesn't cause anywhere near as noticable lag when having no speed restrictions (on sleep 0)

As with a lot of my recent functions, I've tried to keep it simple and maths orientated, so there aren't as many if then else if then else loops. I also only decalre the echos I really need once.

The biggest draw back I don't like in the current code is the two while loops that do the same thing -- print the dashes. I'm not sure how else to get around the problem as the second set of dashes has to go after the greater than signs.

Still, looks pretty nice when running and you should be able to move it about the screen without any major issues (as it backspaces the exact number of characters required; hopefully).

You should get something that looks like this:

%% /uploads/loadingbar.gif; loading bar example %%

As with all my other better Bash stuff, this has been implimented in bashlib (which also got a few bugs fixed today).