(2013-07-30) Bash Timer

More bash functions today -- this time, a timer (using 1/10th of a second per tick):

~~~~
function __timer__ () {
        case ${1} in
                "start")
                        [[ ! ${ms} ]] && ms=0
                        [[ ! ${s} ]] && s=0
                        [[ ! ${m} ]] && m=0
                        [[ ! ${h} ]] && h=0
                        [[ ${ms} == 10 ]] && ms="0" && s=$[${s}+1]
                        [[ ${s} == 60 ]] && s="0" && m=$[${m}+1]
                        [[ ${m} == 60 ]] && m="0" && h=$[${h}+1]
                        [[ ${s} -lt 10 ]] && sR="0${s}" || sR="${s}"
                        [[ ${m} -lt 10 ]] && mR="0${m}" || mR="${m}"
                        [[ ${h} -lt 10 ]] && hR="0${h}" || hR="${h}"
                        echo -ne "${hR}:${mR}:${sR}:${ms}\r\c"
                        ms=$[${ms}+1]
                        sleep 0.1
                ;;
                "stop")
                        echo "${hR}:${mR}:${sR}:${ms}"
                ;;
        esac
}
~~~~

Pretty straight forward usage, works exactly like the spinner (with start / stop technology). 

To see it in action, just run:

~~~~
while true; do
	__timer__ "start"
done
~~~~

I realised after posting that my previous example doesn't really explain much on how to actually make use of the spinner / timer in any real world way.

So to fix that:

~~~~
function __process_pid__ () {
        local process=$(ps xco pid | egrep -c "${1}")
        [[ ${process} != "0" ]] && _process="1" || _process="0"
}

function __forever_a_loop__ () {
        [[ ! ${1} ]] && j=5 || j=${1}
        i=0
        while [[ ${i} -lt ${j} ]]; do
                sleep 0.2
                i=$[${i}+1]
        done
}

__forever_a_loop__ ${1} &
until [[ ${_process} == 0 ]]; do
	__process_pid__ ${!}
        __timer__ "start"
done
echo -n "Done in: "
__timer__ "stop"
~~~~

This will run a simple sleep command in the background and print the timer until the background process has died (for any reason) and then echo "Done in xx:xx:xx:x"

Now, the timing is not accurate to the milisecond, but it does give you a decent idea for how long a process is running and more importantly gives feedback to the end user something is happening. You can also replace the "__timer__" call with "__spinner__" if you didn't want to show the time.

I've added the timer to bashlib, naturally (also made a few minor changes for bug fixing as well).

On the back of the above, I had to add the process_pid command as a sub command of the "__process__" command in bashlib, as that is *really* useful.